1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.channel.nio;
17
18 import java.nio.channels.SelectionKey;
19 import java.util.AbstractSet;
20 import java.util.Arrays;
21 import java.util.Iterator;
22 import java.util.NoSuchElementException;
23 import java.util.Objects;
24
25 final class SelectedSelectionKeySet extends AbstractSet<SelectionKey> {
26
27 SelectionKey[] keys;
28 int size;
29
30 SelectedSelectionKeySet() {
31 keys = new SelectionKey[1024];
32 }
33
34 @Override
35 public boolean add(SelectionKey o) {
36 if (o == null) {
37 return false;
38 }
39
40 if (size == keys.length) {
41 increaseCapacity();
42 }
43
44 keys[size++] = o;
45 return true;
46 }
47
48 @Override
49 public boolean remove(Object o) {
50 return false;
51 }
52
53 @Override
54 public boolean contains(Object o) {
55 SelectionKey[] array = keys;
56 for (int i = 0, s = size; i < s; i++) {
57 SelectionKey k = array[i];
58 if (k.equals(o)) {
59 return true;
60 }
61 }
62 return false;
63 }
64
65 @Override
66 public int size() {
67 return size;
68 }
69
70 @Override
71 public Iterator<SelectionKey> iterator() {
72 return new Iterator<SelectionKey>() {
73 private int idx;
74
75 @Override
76 public boolean hasNext() {
77 return idx < size;
78 }
79
80 @Override
81 public SelectionKey next() {
82 if (!hasNext()) {
83 throw new NoSuchElementException();
84 }
85 return keys[idx++];
86 }
87
88 @Override
89 public void remove() {
90 throw new UnsupportedOperationException();
91 }
92 };
93 }
94
95 void reset() {
96 reset(0);
97 }
98
99 void reset(int start) {
100 Arrays.fill(keys, start, size, null);
101 size = 0;
102 }
103
104 private void increaseCapacity() {
105 SelectionKey[] newKeys = new SelectionKey[keys.length << 1];
106 System.arraycopy(keys, 0, newKeys, 0, size);
107 keys = newKeys;
108 }
109 }