org.mentalog.encoder.ByteOrCharArrayEncoder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of menta-log Show documentation
Show all versions of menta-log Show documentation
A log library that embraces the kiss principle.
package org.mentalog.encoder;
import java.nio.ByteBuffer;
public class ByteOrCharArrayEncoder implements Encoder {
@Override
public boolean encode(Object obj, ByteBuffer bb, int varargsPos, int varargsLen) {
if (obj instanceof byte[]) {
byte[] array = (byte[]) obj;
parseTrimmedString(array, 0, array.length, bb);
return true;
} else if (obj instanceof char[]) {
char[] array = (char[]) obj;
parseTrimmedString(array, 0, array.length, bb);
return true;
}
return false;
}
private final void parseTrimmedString(byte[] src, int position, int length, ByteBuffer bb) {
int start = position;
int end = start + length;
while (start < end && src[start] <= ' ') {
start++;
}
while (end > start && src[end - 1] <= ' ') {
end--;
}
if (start >= end) {
return;
}
for(int i = start; i < end; i++) {
bb.put(src[i]);
}
}
private final void parseTrimmedString(char[] src, int position, int length, ByteBuffer bb) {
int start = position;
int end = start + length;
while (start < end && src[start] <= ' ') {
start++;
}
while (end > start && src[end - 1] <= ' ') {
end--;
}
if (start >= end) {
return;
}
for(int i = start; i < end; i++) {
bb.put((byte) src[i]);
}
}
}