public class MessageArrayBuilder {
private int capacity = 20;
private int length = 0;
public void setCapacity(int capacity) {
if (capacity > 0) {
this.capacity = capacity;
}
}
public MessageArrayBuilder() {}
public MessageArrayBuilder(int capacity) {
setCapacity(capacity);
}
private byte[] array = new byte[capacity];
private int index = 0 ;
public MessageArrayBuilder append(byte b) {
if (index >= array.length) {
byte[] newArray = new byte[array.length + capacity];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[index] = b;
index++;
return this;
}
public MessageArrayBuilder append(byte[] array) {
for (byte b : array) {
append(b);
}
return this;
}
public MessageArrayBuilder append(String string) {
return append(string.getBytes(Charset.forName("GBK")));
}
public void addByte(int i){
append(intToByte(i)[0]);
}
public void addDWORD(int i){
append(intToDWORD(i));
}
public int addDWORDLength(int i){
return intToDWORD(i).length;
}
public void addWORD(int i){
append(intToWORD(i));
}
public void addBCD(String string){
append(hexStringToByte(string));
}
public int addBCDLength(String string){
return hexStringToByte(string).length;
}
public void append(int paramId, String string){
append(paramId, string , true);
}
public void appendBCD(int paramId, String string){
length++;
addWORD(paramId);
addByte(addBCDLength(string));
addBCD(string);
}
public void append(int paramId, String string, boolean fillLength){
length++;
addWORD(paramId);
if(StringUtils.isBlank(string)){
if(fillLength){
addByte(0);
}
return;
}
addByte(string.getBytes().length);
append(string);
}
public void append(int paramId, int latlng){
length++;
addWORD(paramId);
addByte(addDWORDLength(latlng));
addDWORD(latlng);
}
public void insertFirst(byte b){
byte[] array = getBytes();
byte[] newArray = new byte[array.length + capacity];
System.arraycopy(array, 0, newArray, 1, array.length);
newArray[0] = b;
this.array = newArray;
index++;
}
public byte[] getBytes() {
byte[] newArray = new byte[index];
System.arraycopy(array, 0, newArray, 0, index);
return newArray;
}
public int getLength() {
return length;
}
}
消息构造器
最新推荐文章于 2019-08-30 17:54:40 发布