其实ByteString没什么好看的。看之前以为有重要内容,看完后发现没有,不过既然已经看了,就记录下来吧。
ByteString封装了以下几点
1、就是把一些输入类型(字符串/字节数组/ByteBuffer/byte)转成字节数组,并封装成新的ByteString返回。
比如ByteString.of(...)
2、封装了对ByteString的比较、加密操作,方便使用
比如ByteString.encode(...)、base64(...)、md5(...)、sha1()、....
ByteString.startWith(...)、endWith(...)
差不多就这些东西。
public class ByteString implements Serializable, Comparable<ByteString> {
static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/** A singleton empty {@code ByteString}. */
public static final ByteString EMPTY = ByteString.of();
final byte[] data;
transient int hashCode; // Lazily computed; 0 if unknown.
transient String utf8; // Lazily computed.
ByteString(byte[] data) {
this.data = data; // Trusted internal constructor doesn't clone data.
}
/**
* Returns a new byte string containing a clone of the bytes of {@code data}.
*/
public static ByteString of(byte... data) {
if (data == null) {
throw new IllegalArgumentException("data == null");
}
return new ByteString(data.clone());
}
//复制data的缓存中byteCount个字节的内容到新的byte[],返回一个新的ByteString
public static ByteString of(byte[] data, int offset, int byteCount) {
if (data == null) {
throw new IllegalArgumentException("data == null");
}
checkOffsetAndCount(data.length, offset, byteCount);//校验参数
byte[] copy = new byte[byteCount];
System.arraycopy(data, offset, copy, 0, byteCount);
return new ByteString(copy);
}
//复制data的缓存中0-data.remaining()的内容到copy数组,返回新的ByteString
public static ByteString of(ByteBuffer data) {
if (data == null) {
throw new IllegalArgumentException("data == null");
}
byte[] copy = new byte[data.remaining()];//
data.get(copy);
return new ByteString(copy);
}
//把string转byte[]存入新建的ByteString返回,byteString.utf8保存了string的原字符串
public static ByteString encodeUtf8(String s) {
if (s == null) {
throw new IllegalArgumentException("s == null");
}
ByteString byteString = new ByteString(s.getBytes(Util.UTF_8));
byteString.utf8 = s;
return byteString;
}
/** Returns a new byte string containing the {@code charset}-encoded bytes of {@code s}. */
public static ByteString encodeString(String s, Charset charset) {
if (s =