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

com.aliyun.drc.client.message.ByteString Maven / Gradle / Ivy

There is a newer version: 5.0.0.1-cloud.beta
Show newest version
package com.aliyun.drc.client.message;

import java.io.UnsupportedEncodingException;

/**
 * ByteString store an array of bytes and take over all related transfers,
 * such as judge if it should be null, empty or in some an encoding.
 * @author erbai.qzc
 *
 */
public class ByteString {
	private int len;

    private int offset;

    private byte[] bytes;


    public ByteString(byte[] bytes, int len) {
        this.bytes = bytes;
        this.len = len;
    }


    public ByteString(byte[] bytes, int offset, int len) {
        this.bytes = bytes;
        this.len = len;
        this.offset = offset;
    }

    /**
     * Convert the bytes to any encoding.
     *
     * @param encoding the target encoding.
     * @return the encoded string.
     * @throws UnsupportedEncodingException
     */
    public String toString(final String encoding)
            throws UnsupportedEncodingException {

        if (len == 0)
            return new String("");

        if (encoding.equalsIgnoreCase("binary"))
            throw new UnsupportedEncodingException
                    ("field encoding: binary, use getBytes() instead of toString()");

        String realEncoding = encoding;
        if (encoding.isEmpty() || encoding.equalsIgnoreCase("null"))
            realEncoding = "ASCII";
        else if (encoding.equalsIgnoreCase("utf8mb4"))
            realEncoding = "utf8";
        else if (encoding.equalsIgnoreCase("latin1"))
            realEncoding = "cp1252";
        else if (encoding.equalsIgnoreCase("latin2"))
            realEncoding = "iso-8859-2";
        return new String(bytes, offset, len, realEncoding);
    }

    public String toString() {
        if (len == 0)
            return "";
        byte[] byteArray = this.bytes;
        char[] charArray = new char[len];
        for (int i = 0; i < len; i++) {
            charArray[i] = (char) byteArray[i + offset];
        }
        return String.valueOf(charArray);
    }

    public byte[] getBytes() {
        byte t[] = new byte[len];
        System.arraycopy(bytes, offset, t, 0, len);
        return t;
    }

    public int getLen() {
        return len;
    }

    public int getOffset() {
        return offset;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy