Files
min-dev-java/src/main/java/component/MutableDangerousField.java
T

140 lines
3.9 KiB
Java

package component;
import encoding.*;
/*
* @Author: Wang Feng
* @Description: 表示一个MIN包格式中的可变非受保护区
* @Version: 1.0.0
* @Date: 20:34 2021/3/9
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
*/
public class MutableDangerousField implements TlvComponentBase, IEncodingAble {
private ElementContainer blocks= new ElementContainer();
public MutableDangerousField(){
}
/**
* 往可变非受保护区添加一个Block
*
* @param block
*/
public void addBlock(Block block) {
blocks.addElement(block);
}
/**
* 获取可变非受保护区指定位置的 Block
*
* @return
*/
public Block getBlock(int index) throws ComponentException {
try {
return this.blocks.getBlock(index);
} catch (BlockException e) {
throw new ComponentException("MutableDangerousField.getBlock: " + e.getMessage());
}
}
/**
* 清空可变非受保护区中,所有的子 Block
*/
public void clearBlocks() {
this.blocks.clear();
}
/**
* 获取可变非受保护区所有的 Block
*
* @return
*/
public ElementContainer getBlocks() {
return this.blocks;
}
/**
* 获取可变非受保护区中,第一个指定TLV-TYPE的子 TLV Block
*
* @return
*/
public Block getBlockByType(VlInt tlvType) throws ComponentException {
try {
return this.blocks.getBlockByType(tlvType);
} catch (BlockException e) {
throw new ComponentException("MutableDangerousField.getBlockByType: " + e.getMessage());
}
}
/**
* 将可变非受保护区线速编码为一个 TLV
*
* @param encoder
* @return
*/
@Override
public int wireEncode(Encoder encoder) throws ComponentException {
try {
// 如果可变非受保护区没有任何子 TLV,则可以去掉可变非受保护区 TLV
if (this.blocks.length() == 0) {
return 0;
}
int totalLength = 0;
// 编码TLV-VALUE
// 反向遍历,可以保证解码的时候正向输出
for (int i = this.blocks.length() - 1; i >= 0; i--) {
int tmplen = encoder.prependBlock(this.blocks.getBlock(i));
if (tmplen < 0) {
return -1;
}
totalLength += tmplen;
}
// 编码 TLV-LENGTH
int tmplen = encoder.prependVarNumber(new VlInt(totalLength));
if (tmplen < 0) {
return -1;
}
totalLength += tmplen;
// 编码 TLV-TYPE
tmplen = encoder.prependVarNumber(new VlInt(TLV.TlvMutableDangerousField));
if (tmplen < 0) {
return -1;
}
totalLength += tmplen;
return totalLength;
} catch (EncoderException | BlockException e) {
throw new ComponentException("MutableDangerousField.wireEncode: " + e.getMessage());
}
}
/**
* 从 TLV Block 中解码出一个 ReadOnlyField
*
* @param block
* @return
*/
@Override
public boolean wireDecode(Block block) throws ComponentException {
// 检查 Type 是否正确
if (!TLV.expectType(block.getType(), new VlInt(TLV.TlvMutableDangerousField))) {
return false;
}
// 解析子 TLV
try {
if (!block.parseSubElements()) {
return false;
}
} catch (BlockException e) {
throw new ComponentException("MutableDangerousField.wireDecode: " + e.getMessage());
}
this.blocks = block.getSubElements();
return true;
}
}