All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.mentalog.encoder.ByteOrCharArrayEncoder Maven / Gradle / Ivy

There is a newer version: 2.1.2
Show newest version
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]);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy