summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/io/Blob.java
blob: dc73581df598a0c8b05238fa631531b362684960 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.io;

import java.nio.ByteBuffer;

/**
 * A Blob contains opaque data in the form of a byte array.
 **/
public class Blob {

    /**
     * Shared empty array.
     **/
    private static byte[] empty = new byte[0];

    /**
     * Internal data, will never be 'null'.
     **/
    private byte[] data;

    /**
     * Create a Blob containing an empty byte array.
     **/
    public Blob() {
        data = empty;
    }

    /**
     * Create a Blob containg a copy of a subset of the given byte
     * array.
     **/
    public Blob(byte[] src, int offset, int length) {
        data = new byte[length];
        System.arraycopy(src, offset, data, 0, length);
    }

    /**
     * Create a Blob containing a copy of the given byte array.
     **/
    public Blob(byte[] src) {
        this(src, 0, src.length);
    }

    /**
     * Create a Blob containing a copy of the data held by the given
     * blob.
     **/
    public Blob(Blob src) {
        this(src.data);
    }

    /**
     * Create a Blob containing a number of bytes read from a byte
     * buffer.
     **/
    public Blob(ByteBuffer src, int length) {
        data = new byte[length];
        src.get(data);
    }

    /**
     * Create a Blob containing all bytes that could be read from a
     * byte buffer.
     **/
    public Blob(ByteBuffer src) {
        this(src, src.remaining());
    }

    /**
     * Obtain the internal data held by this object.
     *
     * @return internal data
     **/
    public byte[] get() {
        return data;
    }

    /**
     * Write the data held by this object to the given byte buffer.
     *
     * @param dst where to write the contained data
     **/
    public void write(ByteBuffer dst) {
        dst.put(data);
    }
}