org.zodiac.netty.marshallers.StringMarshaller Maven / Gradle / Ivy
package org.zodiac.netty.marshallers;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.util.CharsetUtil;
import static org.zodiac.netty.marshallers.NettyContentMarshallers.findCharset;
import java.nio.charset.Charset;
import org.zodiac.sdk.toolkit.marshallers.Marshaller;
final class StringMarshaller implements Marshaller {
@Override
public String read(ByteBuf data, Object[] hints) throws Exception {
byte[] bytes = new byte[data.readableBytes()];
data.getBytes(0, bytes);
Charset charset = findCharset(hints);
if (charset == null) {
charset = NettyContentMarshallers.findHint(Charset.class, hints, CharsetUtil.UTF_8);
}
return new String(bytes, charset);
}
@Override
public void write(String obj, ByteBuf into, Object[] hints) throws Exception {
Charset charset = findCharset(hints);
if (CharsetUtil.UTF_8.equals(charset)) {
ByteBufUtil.writeUtf8(into, obj);
} else if (CharsetUtil.US_ASCII.equals(charset)) {
ByteBufUtil.writeAscii(into, obj);
} else {
byte[] bytes = obj.getBytes(charset);
into.writeBytes(bytes);
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy