View Javadoc
1   /*
2    * Copyright 2016 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    *   http://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.netty.channel.kqueue;
17  
18  import io.netty.util.internal.PlatformDependent;
19  
20  import static io.netty.channel.unix.Limits.SIZEOF_JLONG;
21  
22  final class NativeLongArray {
23      private long memoryAddress;
24      private int capacity;
25      private int size;
26  
27      NativeLongArray(int capacity) {
28          if (capacity < 1) {
29              throw new IllegalArgumentException("capacity must be >= 1 but was " + capacity);
30          }
31          memoryAddress = PlatformDependent.allocateMemory(capacity * SIZEOF_JLONG);
32          this.capacity = capacity;
33      }
34  
35      void add(long value) {
36          checkSize();
37          PlatformDependent.putLong(memoryOffset(size++), value);
38      }
39  
40      void clear() {
41          size = 0;
42      }
43  
44      boolean isEmpty() {
45          return size == 0;
46      }
47  
48      void free() {
49          PlatformDependent.freeMemory(memoryAddress);
50          memoryAddress = 0;
51      }
52  
53      long memoryAddress() {
54          return memoryAddress;
55      }
56  
57      long memoryAddressEnd() {
58          return memoryOffset(size);
59      }
60  
61      private long memoryOffset(int index) {
62          return memoryAddress + index * SIZEOF_JLONG;
63      }
64  
65      private void checkSize() {
66          if (size == capacity) {
67              realloc();
68          }
69      }
70  
71      private void realloc() {
72          // Double the capacity while it is "sufficiently small", and otherwise increase by 50%.
73          int newLength = capacity <= 65536 ? capacity << 1 : capacity + capacity >> 1;
74          long newMemoryAddress = PlatformDependent.reallocateMemory(memoryAddress, newLength * SIZEOF_JLONG);
75          if (newMemoryAddress == 0) {
76              throw new OutOfMemoryError("unable to allocate " + newLength + " new bytes! Existing capacity is: "
77                      + capacity);
78          }
79          memoryAddress = newMemoryAddress;
80          capacity = newLength;
81      }
82  
83      @Override
84      public String toString() {
85          return "memoryAddress: " + memoryAddress + " capacity: " + capacity + " size: " + size;
86      }
87  }