]> git.basschouten.com Git - openhab-addons.git/blob
b157788add27dfa1d16c7ecd141694af97bf6d7f
[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         return wrapped.value(flipped);
48     }
49
50     @Override
51     public ByteBuffer bytesInternal(T value) {
52         return flip(wrapped.bytes(value));
53     }
54
55     public static ByteBuffer flip(ByteBuffer buf) {
56         buf.rewind();
57
58         ByteBuffer ret = ByteBuffer.allocate(buf.limit());
59
60         for (int i = buf.limit() - 1; i >= 0; i--) {
61             ret.put(buf.get(i));
62         }
63
64         ret.rewind();
65
66         return ret;
67     }
68 }