package component; import encoding.*; /* * @Author: Wang Feng * @Description: * @Version: 1.0.0 * @Date: 10:20 2021/3/9 * @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室 */ public class TTL implements IEncodingAble { /** * 表示一个 TTL Tlv * todo: 后台使用的uint64,故这里用long表示,则理论上可能越界 * // @Description: * 1. 格式如下: * TTL = TTL-TYPE TLV-LENGTH NonNegativeInteger */ private long ttl; public TTL() { } public TTL(Block block) throws ComponentException { buildTTLByBlock(block); } /** * 根据 TLV Block 初始化一个 TTL * * @param block * @return */ public boolean buildTTLByBlock(Block block) throws ComponentException { return this.wireDecode(block); } /** * 获取 TTL 值 * * @return */ public long ttl() { return this.ttl; } /** * 设置 TTL 值 * * @param ttl */ public void setTtl(long ttl) { this.ttl = ttl; } /** * 将 TTL 线速编码为一个 TLV * * @param encoder * @return */ @Override public int wireEncode(Encoder encoder) throws ComponentException { try { int totalLength = 0; // 编码 TLV-VALUE int tmpLen = encoder.prependNonNegativeInteger(this.ttl); if (tmpLen <= 0) { return -1; } totalLength += tmpLen; // 编码 TLV-LENGTH tmpLen = encoder.prependVarNumber(new VlInt(totalLength)); if (tmpLen <= 0) { return -1; } totalLength += tmpLen; // 编码 TLV-TYPE tmpLen = encoder.prependVarNumber(new VlInt(TLV.TlvTTL)); if (tmpLen <= 0) { return -1; } totalLength += tmpLen; return totalLength; } catch (EncoderException e) { throw new ComponentException("TTL.wireEncode: " + e.getMessage()); } } /** * 从 TLV Block 中解码出一个 TTL * * @param block * @return */ @Override public boolean wireDecode(Block block) throws ComponentException { try { // 检查Type是否正确 if (!TLV.expectType(block.getType(), new VlInt(TLV.TlvTTL))) { return false; } long value = TLV.readNonNegativeInteger(block.getValue(), 0, block.getLength().getVlIntValue2Int()); if (value < 0) { return false; } this.ttl = value; return true; } catch (TLVException | VlIntException e) { throw new ComponentException("TTL.wireDecode: " + e.getMessage()); } } }