Files
min-dev-java/src/main/java/packet/LpPacket.java
T

116 lines
3.4 KiB
Java

package packet;
import component.ComponentException;
import component.LpPacketHeader;
import component.Payload;
import encoding.*;
/*
* @Author: Wang Feng
* @Description:
* @Version: 1.0.0
* @Date: 17:33 2021/4/2
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
*/
public class LpPacket implements IEncodingAble {
public LpPacketHeader lpPacketHeader=new LpPacketHeader();
public Payload payload=new Payload();
public LpPacket(){
}
public LpPacket(LpPacketHeader lpPacketHeader,Payload payload){
this.lpPacketHeader=lpPacketHeader;
this.payload=payload;
}
/**
* 将 LpPacket 线速编码为一个 TLV
* @param encoder
* @return
* @throws ComponentException
* @throws PacketException
*/
@Override
public int wireEncode(Encoder encoder) throws PacketException {
try {
int totalLength = 0;
// 编码 TLV-VALUE
// LpHeader
int tmpLen = this.lpPacketHeader.wireEncode(encoder);
if(tmpLen<0){
return -1;
}
totalLength+=tmpLen;
// Fragment
tmpLen = this.payload.wireEncode(encoder);
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.TlvLpPacket));
if(tmpLen<0){
return -1;
}
totalLength+=tmpLen;
return totalLength;
} catch (ComponentException | EncoderException e) {
throw new PacketException("LpPacket.wireEncode: "+e.getMessage());
}
}
/**
* 从 Block TLV 中解码出一个 LpPacket
* @param block
* @return
* @throws ComponentException
* @throws PacketException
*/
@Override
public boolean wireDecode(Block block) throws PacketException {
try {
// 检查 Type 是否正确
if (!TLV.expectType(block.getType(), new VlInt(TLV.TlvLpPacket))) {
return false;
}
// 解析子组件
if(!block.parseSubElements()){
return false;
}
ElementContainer elementContainer=block.getSubElements();
for (int i = 0; i < elementContainer.length(); i++) {
Block newBlock=elementContainer.getBlock(i);
int type=newBlock.getType().getVlIntValue2Int();
switch (type){
case TLV.TlvLpPacketHeader:
if(!this.lpPacketHeader.wireDecode(newBlock)){
return false;
}
break;
case TLV.TlvPayload:
if(!this.payload.wireDecode(newBlock)){
return false;
}
break;
}
}
return true;
} catch (VlIntException | BlockException | ComponentException e) {
throw new PacketException("LpPacket.wireDecode: "+e.getMessage());
}
}
}