]> git.basschouten.com Git - openhab-addons.git/blob
07de7e342f3e0b35bde89d4deeb3c80933aedb3a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.lifx.internal.fields;
14
15 import java.nio.ByteBuffer;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * Reads a wrapped field in reversed byte order.
21  *
22  * @author Tim Buckley - Initial contribution
23  */
24 @NonNullByDefault
25 public class LittleField<T> extends Field<T> {
26
27     private final Field<T> wrapped;
28
29     public LittleField(Field<T> wrapped) {
30         super(wrapped.length);
31
32         this.wrapped = wrapped;
33     }
34
35     @Override
36     public int defaultLength() {
37         return wrapped.defaultLength();
38     }
39
40     @Override
41     public T value(ByteBuffer bytes) {
42         byte[] field = new byte[wrapped.length];
43         bytes.get(field);
44
45         ByteBuffer flipped = flip(ByteBuffer.wrap(field));
46
47         T value = wrapped.value(flipped);
48
49         return value;
50     }
51
52     @Override
53     public ByteBuffer bytesInternal(T value) {
54         return flip(wrapped.bytes(value));
55     }
56
57     public static ByteBuffer flip(ByteBuffer buf) {
58         buf.rewind();
59
60         ByteBuffer ret = ByteBuffer.allocate(buf.limit());
61
62         for (int i = buf.limit() - 1; i >= 0; i--) {
63             ret.put(buf.get(i));
64         }
65
66         ret.rewind();
67
68         return ret;
69     }
70 }