mirror of
https://gitee.com/willfree/min-dev-java.git
synced 2026-10-04 19:42:01 +08:00
98 lines
2.7 KiB
Java
98 lines
2.7 KiB
Java
package encoding;
|
|
|
|
import component.CanBePrefix;
|
|
|
|
/*
|
|
* @Author: Wang Feng
|
|
* @Description: 利用对接口的函数回调,实现对任意实现了 IEncodingAble 接口的对象进行自编码
|
|
* @Version: 1.0.0
|
|
* @Date: 16:17 2021/3/15
|
|
* @Copyright: MIN-Group;国家重大科技基础设施——未来网络北大实验室;深圳市信息论与未来网络重点实验室
|
|
*/
|
|
public class SelfEncodingBase {
|
|
|
|
// 用来实现自编码的辅助结构
|
|
private Block rawBlock;
|
|
// 存放回调的函数
|
|
// private IEncodingAble iEncodingAble;
|
|
|
|
public SelfEncodingBase(){
|
|
}
|
|
|
|
/**
|
|
* 获取编码后的Block
|
|
* @return
|
|
*/
|
|
public Block getRawBlock(){
|
|
return rawBlock;
|
|
}
|
|
|
|
/**
|
|
* 设置回调函数(接口的函数)
|
|
* @param iEncodingAble
|
|
*/
|
|
// public void setiEncodingAble(IEncodingAble iEncodingAble) {
|
|
// this.iEncodingAble = iEncodingAble;
|
|
// }
|
|
|
|
/**
|
|
* 对一个实现了 IEncodingAble 接口的对象进行自编码
|
|
* // @Description:
|
|
* // 1. 用 rawBlock缓存编码的结果;
|
|
* // 2. 如果 rawBlock不为空,且指向一个有效的 Block,则直接返回raw
|
|
* // 3. 如果 rawBlock为空,或者指向的不是一个有效的 Block,则将对象编码为 Block 之后返回,同时用 raw指针缓存编码的结果
|
|
* @param iEncodingAble
|
|
* @return
|
|
*/
|
|
public Block selfWireEncode(IEncodingAble iEncodingAble){
|
|
// this.setiEncodingAble(iEncodingAble);
|
|
if((this.rawBlock!=null)&&this.rawBlock.isValid()){
|
|
return this.rawBlock;
|
|
}
|
|
|
|
Block block=easyEncoder(iEncodingAble);
|
|
if(block==null){
|
|
return null;
|
|
}
|
|
this.rawBlock=block;
|
|
return block;
|
|
}
|
|
|
|
/**
|
|
* 自编码辅助函数
|
|
* 利用对接口的函数回调,实现对任意实现了 IEncodingAble 接口的对象进行自编码
|
|
* @param iEncodingAble
|
|
* @return
|
|
*/
|
|
private Block easyEncoder(IEncodingAble iEncodingAble){
|
|
Encoder encoder=new Encoder();
|
|
|
|
// 首先测量目标 TLV 的大小
|
|
encoder.estimatorReset();
|
|
int targetLen=iEncodingAble.wireEncode(encoder);
|
|
if(targetLen<=0){
|
|
return null;
|
|
}
|
|
|
|
// 编码初始化
|
|
if(!encoder.encoderReset(new SizeT(targetLen),new SizeT(0))){
|
|
return null;
|
|
}
|
|
|
|
// 实际执行编码
|
|
targetLen=iEncodingAble.wireEncode(encoder);
|
|
if(targetLen<=0){
|
|
return null;
|
|
}
|
|
|
|
byte[] buffer=encoder.getBuffer();
|
|
if((buffer==null)||buffer.length==0){
|
|
return null;
|
|
}
|
|
|
|
// 返回编码的结果
|
|
return Block.createBlockByBuffer(buffer,true);
|
|
}
|
|
|
|
}
|