org.openfast.template.type.codec.AsciiString
public byte[] encodeValue(ScalarValue value) { if ((value == null) || value.isNull()) { throw new IllegalStateException("Only nullable strings can represent null values."); } String string = value.toString(); if ((string != null) && (string.length() == 0)) { return TypeCodec.NULL_VALUE_ENCODING; } if (string.startsWith(ZERO_TERMINATOR)) { return ZERO_PREAMBLE; } return string.getBytes(); } public ScalarValue decode(InputStream in) { int byt; ByteArrayOutputStream buffer = Global.getBuffer(); try { do { byt = in.read(); if (byt < 0) { Global.handleError(FastConstants.END_OF_STREAM, "The end of the input stream has been reached."); return null; // short circuit if global error handler does not throw exception } buffer.write(byt); } while ((byt & 0x80) == 0); } catch (IOException e) { Global.handleError(FastConstants.IO_ERROR, "A IO error has been encountered while decoding.", e); return null; // short circuit if global error handler does not throw exception } byte[] bytes = buffer.toByteArray(); //复原最后一个字节为真实数据 bytes[bytes.length - 1] &= 0x7f; if (bytes[0] == 0) { if (!ByteUtil.isEmpty(bytes)) Global.handleError(FastConstants.R9_STRING_OVERLONG, null); if (bytes.length > 1 && bytes[1] == 0) return new StringValue("\u0000"); return new StringValue(""); } return new StringValue(new String(bytes)); } 字节流编码类org.openfast.template.type.codec.ByteVectorType
注意:字节流类型不使用停止位
public byte[] encode(ScalarValue value) { byte[] bytes = value.getBytes(); int lengthSize = IntegerCodec.getUnsignedIntegerSize(bytes.length); byte[] encoding = new byte[bytes.length + lengthSize]; byte[] length = TypeCodec.UINT.encode(new IntegerValue(bytes.length)); //数据流所占长度 System.arraycopy(length, 0, encoding, 0, lengthSize); //数据 System.arraycopy(bytes, 0, encoding, lengthSize, bytes.length); return encoding; } public ScalarValue decode(InputStream in) { //解析字节流的长度 int length = ((IntegerValue) TypeCodec.UINT.decode(in)).value; byte[] encoding = new byte[length]; //读取字节流 for (int i = 0; i < length; i++) try { int nextByte = in.read(); if (nextByte < 0) { Global.handleError(FastConstants.END_OF_STREAM, "The end of the input stream has been reached."); return null; // short circuit if global error handler does not throw exception } encoding[i] = (byte) nextByte; } catch (IOException e) { Global.handleError(FastConstants.IO_ERROR, "A IO error has been encountered while decoding.", e); return null; // short circuit if global error handler does not throw exception } return new ByteVectorValue(encoding); } Unicode字符串类型编码类org.openfast.template.type.codec.UnicodeString
这个类型和上面的字节流编码类逻辑一样。