com.flybotix.hfr.codex.encode.AEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of highfrequencyrobots Show documentation
Show all versions of highfrequencyrobots Show documentation
A way for wifi robots and IoT devices to quickly send compressed data arrays across a network.
package com.flybotix.hfr.codex.encode;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import com.flybotix.hfr.codex.CodexMetadata;
import com.flybotix.hfr.codex.CodexOf;
import com.flybotix.hfr.util.lang.EnumUtils;
import com.flybotix.hfr.util.log.ILog;
import com.flybotix.hfr.util.log.Logger;
import com.flybotix.hfr.codex.Codex;
public abstract class AEncoder & CodexOf>{
private static final ILog mLog = Logger.createLog(AEncoder.class);
private final Class mEnumClass;
protected final int mLength;
protected final int mBitSetByteLength;
protected final int mEnumHash;
public AEncoder(Class pEnum) {
mEnumClass = pEnum;
mLength = EnumSet.allOf(pEnum).size();
mEnumHash = EnumUtils.hashOf(pEnum);
mBitSetByteLength = (mLength + Byte.SIZE-1) / Byte.SIZE;
}
public int getMsgId() {
return mEnumHash;
}
public Class getEnum() {
return mEnumClass;
}
public abstract int getBufferSizeInBytes();
public abstract V getDefaultValue();
public abstract V[] generateEmptyArray();
public abstract AEncoder createClone();
public byte[] encode(Codex pData) {
byte[] body = encodeImpl(pData);
byte[] header = pData.meta().encode();
mLog.debug("Header: " + pData.meta());
return ByteBuffer.allocate(header.length + body.length).put(header).put(body).array();
}
public Codex decode(ByteBuffer pData) {
CodexMetadata header = CodexMetadata.parse(mEnumClass, pData);
mLog.debug("Header: " + header);
Codex body = decodeImpl(pData);
body.setMetadata(header);
return body;
}
protected abstract Codex decodeImpl(ByteBuffer pData);
protected abstract byte[] encodeImpl(Codex pData);
}