RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
ReadOnlyPrimitiveLongSet.java
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5package org.wpilib.units.collections;
6
7import java.util.Arrays;
8import java.util.Iterator;
9import java.util.NoSuchElementException;
10import java.util.Set;
11import java.util.stream.LongStream;
12
14public class ReadOnlyPrimitiveLongSet implements Iterable<Long> {
15 private final long[] m_values;
16
22 @SuppressWarnings({"PMD.ForLoopCanBeForeach", "ForLoopReplaceableByForEach"})
23 public ReadOnlyPrimitiveLongSet(long... values) {
24 // initial size is the upper limit
25 long[] uniqueValues = new long[values.length];
26 int numUniqueValues = 0;
27 boolean seenZero = false;
28
29 // copy the set of unique values to our array
30 // using indexed for-loops to avoid allocations
31 copyLoop:
32 for (int i = 0; i < values.length; i++) {
33 long value = values[i];
34 if (value == 0 && !seenZero) {
35 // special case to support zero
36 seenZero = true;
37 } else {
38 for (int j = 0; j < uniqueValues.length; j++) {
39 long uniqueValue = uniqueValues[j];
40 if (uniqueValue == value) {
41 continue copyLoop;
42 }
43 }
44 }
45 uniqueValues[numUniqueValues] = value;
46 numUniqueValues++;
47 }
48
49 if (numUniqueValues == values.length) {
50 // all input values were unique, no need to truncate
51 m_values = uniqueValues;
52 } else {
53 // truncate the array to remove trailing empty space
54 m_values = Arrays.copyOf(uniqueValues, numUniqueValues);
55 }
56 }
57
64 public boolean contains(long value) {
65 for (long mValue : m_values) {
66 if (mValue == value) {
67 return true;
68 }
69 }
70 return false;
71 }
72
78 public int size() {
79 return m_values.length;
80 }
81
87 public boolean isEmpty() {
88 return size() == 0;
89 }
90
97 public LongStream stream() {
98 return Arrays.stream(m_values);
99 }
100
106 public long[] toArray() {
107 return Arrays.copyOf(m_values, m_values.length);
108 }
109
110 @Override
111 public Iterator<Long> iterator() {
112 return new Iterator<>() {
113 private int m_index = 0;
114
115 @Override
116 public boolean hasNext() {
117 return m_index < ReadOnlyPrimitiveLongSet.this.size();
118 }
119
120 @Override
121 public Long next() {
122 if (!hasNext()) {
123 throw new NoSuchElementException();
124 }
125
126 return ReadOnlyPrimitiveLongSet.this.m_values[m_index++];
127 }
128 };
129 }
130}