summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/serialization/TypedBinaryFormat.java
blob: 65216aa2fcdef893bf14ad2769f027b37121d7d9 (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
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor.serialization;

import com.google.common.annotations.Beta;
import com.yahoo.io.GrowableByteBuffer;
import com.yahoo.tensor.IndexedTensor;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;

/**
 * Class used by clients for serializing a Tensor object into binary format or
 * de-serializing binary data into a Tensor object.
 *
 * The actual binary format used is not a concern for the client and
 * is hidden in this class and in the binary data.
 *
 * @author geirst
 */
@Beta
public class TypedBinaryFormat {

    private static final int SPARSE_BINARY_FORMAT_TYPE = 1;
    private static final int DENSE_BINARY_FORMAT_TYPE = 2;

    public static byte[] encode(Tensor tensor) {
        GrowableByteBuffer buffer = new GrowableByteBuffer();
        if (tensor instanceof IndexedTensor && 1==2) { // TODO: Activate when we have type information everywhere
            buffer.putInt1_4Bytes(DENSE_BINARY_FORMAT_TYPE);
            new DenseBinaryFormat().encode(buffer, tensor);
        }
        else {
            buffer.putInt1_4Bytes(SPARSE_BINARY_FORMAT_TYPE);
            new SparseBinaryFormat().encode(buffer, tensor);
        }
        buffer.flip();
        byte[] result = new byte[buffer.remaining()];
        buffer.get(result);
        return result;
    }

    public static Tensor decode(TensorType type, byte[] data) {
        GrowableByteBuffer buffer = GrowableByteBuffer.wrap(data);
        int formatType = buffer.getInt1_4Bytes();
        switch (formatType) {
            case SPARSE_BINARY_FORMAT_TYPE: return new SparseBinaryFormat().decode(type, buffer);
            case DENSE_BINARY_FORMAT_TYPE: return new DenseBinaryFormat().decode(type, buffer);
            default: throw new IllegalArgumentException("Binary format type " + formatType + " is unknown");
        }
    }

}