1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.hardware.camera2.marshal.impl;
17
18import static android.hardware.camera2.impl.CameraMetadataNative.*;
19import static android.hardware.camera2.marshal.MarshalHelpers.*;
20
21import android.hardware.camera2.marshal.Marshaler;
22import android.hardware.camera2.marshal.MarshalQueryable;
23import android.hardware.camera2.utils.TypeReference;
24
25import java.nio.ByteBuffer;
26
27/**
28 * Marshal fake native enums (ints): TYPE_BYTE <-> int/Integer
29 */
30public class MarshalQueryableNativeByteToInteger implements MarshalQueryable<Integer> {
31
32    private static final int UINT8_MASK = (1 << Byte.SIZE) - 1;
33
34    private class MarshalerNativeByteToInteger extends Marshaler<Integer> {
35        protected MarshalerNativeByteToInteger(TypeReference<Integer> typeReference,
36                int nativeType) {
37            super(MarshalQueryableNativeByteToInteger.this, typeReference, nativeType);
38        }
39
40        @Override
41        public void marshal(Integer value, ByteBuffer buffer) {
42            buffer.put((byte)(int)value); // truncate down to byte
43        }
44
45        @Override
46        public Integer unmarshal(ByteBuffer buffer) {
47            // expand unsigned byte to int; avoid sign extension
48            return buffer.get() & UINT8_MASK;
49        }
50
51        @Override
52        public int getNativeSize() {
53            return SIZEOF_BYTE;
54        }
55    }
56
57    @Override
58    public Marshaler<Integer> createMarshaler(TypeReference<Integer> managedType,
59            int nativeType) {
60        return new MarshalerNativeByteToInteger(managedType, nativeType);
61    }
62
63    @Override
64    public boolean isTypeMappingSupported(TypeReference<Integer> managedType, int nativeType) {
65        return (Integer.class.equals(managedType.getType())
66                || int.class.equals(managedType.getType())) && nativeType == TYPE_BYTE;
67    }
68
69
70}
71