1 /*
2 * Copyright © 2016 Greg Chabala
3 *
4 * This file is part of brick-control-lab.
5 *
6 * brick-control-lab is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * brick-control-lab is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with brick-control-lab. If not, see http://www.gnu.org/licenses/.
18 */
19 package org.chabala.brick.controllab;
20
21 import java.util.Collections;
22 import java.util.EnumSet;
23 import java.util.Set;
24
25 /**
26 * Identifiers for the output ports on the control lab.
27 */
28 public enum OutputId {
29 /** Output A. */ A,
30 /** Output B. */ B,
31 /** Output C. */ C,
32 /** Output D. */ D,
33 /** Output E. */ E,
34 /** Output F. */ F,
35 /** Output G. */ G,
36 /** Output H. */ H;
37
38 /**
39 * Convenience constant for specifying all output ports.
40 */
41 public static final Set<OutputId> ALL = Collections.unmodifiableSet(EnumSet.allOf(OutputId.class));
42
43 /**
44 * Encodes values from a {@link Set} of {@link Enum}s to a byte. Uses the
45 * ordinal of the Enum as the position of the bit in the byte to set high.
46 *
47 * @param set set of values to be encoded
48 * @param <T> type of Enum, only used with {@link OutputId} internally
49 * @return a byte with high bits relating to the values in the set
50 */
51 public static <T extends Enum<T>> byte encodeSetToByte(Set<T> set) {
52 byte r = 0;
53 for (T value : set) {
54 r |= 1 << value.ordinal();
55 }
56 return r;
57 }
58
59 private static final OutputId[] ENUM_VALUES = values();
60
61 /**
62 * Decodes a byte into a {@link Set} of {@link OutputId}s.
63 * @param b byte where each bit corresponds to the ordinal of an Output
64 * @return a Set containing the desired Outputs
65 */
66 public static Set<OutputId> decodeByteToSet(byte b) {
67 Set<OutputId> enumSet = EnumSet.noneOf(OutputId.class);
68 int byteAsInt = Byte.toUnsignedInt(b);
69 for (int bit = 0; bit < Byte.SIZE; bit++) {
70 if ((byteAsInt & 1 << bit) > 0) {
71 enumSet.add(ENUM_VALUES[bit]);
72 }
73 }
74 return enumSet;
75 }
76 }