View Javadoc
1   /*
2    * Copyright 2013 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty5.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  
24  final class SelectedSelectionKeySet extends AbstractSet<SelectionKey> {
25  
26      SelectionKey[] keys;
27      int size;
28  
29      SelectedSelectionKeySet() {
30          keys = new SelectionKey[1024];
31      }
32  
33      @Override
34      public boolean add(SelectionKey o) {
35          if (o == null) {
36              return false;
37          }
38  
39          keys[size++] = o;
40          if (size == keys.length) {
41              increaseCapacity();
42          }
43  
44          return true;
45      }
46  
47      @Override
48      public boolean remove(Object o) {
49          return false;
50      }
51  
52      @Override
53      public boolean contains(Object o) {
54          return false;
55      }
56  
57      @Override
58      public int size() {
59          return size;
60      }
61  
62      @Override
63      public Iterator<SelectionKey> iterator() {
64          return new Iterator<>() {
65              private int idx;
66  
67              @Override
68              public boolean hasNext() {
69                  return idx < size;
70              }
71  
72              @Override
73              public SelectionKey next() {
74                  if (!hasNext()) {
75                      throw new NoSuchElementException();
76                  }
77                  return keys[idx++];
78              }
79  
80              @Override
81              public void remove() {
82                  throw new UnsupportedOperationException();
83              }
84          };
85      }
86  
87      void reset() {
88          reset(0);
89      }
90  
91      void reset(int start) {
92          Arrays.fill(keys, start, size, null);
93          size = 0;
94      }
95  
96      private void increaseCapacity() {
97          SelectionKey[] newKeys = new SelectionKey[keys.length << 1];
98          System.arraycopy(keys, 0, newKeys, 0, size);
99          keys = newKeys;
100     }
101 }