FixedLengthStringCodec implements Codec<String> { public void encode(String value, BitChannel channel, Resolver resolver) throws IOException { int size = sizeExpr.eval(resolver); ByteBuffer bytebuffer = ByteBuffer.allocate(size); encoder.encode(CharBuffer.wrap(value), bytebuffer, true); if (bytebuffer.position() < size) { bytebuffer.put(new byte[size - bytebuffer.position()]); } bytebuffer.flip(); byte[] bytes = new byte[size]; bytebuffer.get(bytes); for (int i = 0; i < bytes.length; i++) { bytes[i] = byteConverter.revert(bytes[i]); } channel.write(bytes, 0, size); } FixedLengthStringCodec(Charset encoding,
                                  Expression<Integer, Resolver> sizeExpr, String match,
                                  BoundString.ByteConverter byteConverter); String decode(BitBuffer buffer, Resolver resolver,
                         Builder builder); void encode(String value, BitChannel channel, Resolver resolver); Class<?>[] getTypes(); Expression<Integer, Resolver> getSize(); Class<?> getType(); CodecDescriptor getCodecDescriptor();  }
@Test public void shouldEncodeCorrectly() throws IOException, NullPointerException { Charset charset = Charset.availableCharsets().get(BoundString.Encoding.ASCII); ByteArrayOutputStream out = new ByteArrayOutputStream(); BitChannel channel = new OutputStreamBitChannel(out); when(sizeExpr.eval(Matchers.any(Resolver.class))).thenReturn(4); FixedLengthStringCodec codec = new FixedLengthStringCodec(charset, sizeExpr, null, new BoundString.NullConverter()); codec.encode("Whatever", channel, resolver); out.flush(); byte[] result = out.toByteArray(); assertThat(result.length, is(4)); assertThat(new String(result, "US-ASCII"), is("What")); }