Okio源码阅读笔记(三)ByteString

其实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 =
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值