View Javadoc
1   /*
2    * Copyright 2024 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.netty.channel.uring;
17  
18  import io.netty.channel.unix.Buffer;
19  import io.netty.util.internal.CleanableDirectBuffer;
20  
21  import java.nio.ByteBuffer;
22  import java.util.Arrays;
23  
24  final class MsgHdrMemoryArray {
25      static final long NO_ID = 0;
26  
27      private final MsgHdrMemory[] hdrs;
28      private final int capacity;
29      private final long[] ids;
30      private final CleanableDirectBuffer msgHdrMemoryArrayMemoryCleanable;
31      private boolean released;
32      private int idx;
33  
34      MsgHdrMemoryArray(short capacity) {
35          assert capacity >= 0;
36          this.capacity = capacity;
37          hdrs = new MsgHdrMemory[capacity];
38          ids = new long[capacity];
39          int total = MsgHdrMemory.MSG_HDR_SIZE * capacity;
40          this.msgHdrMemoryArrayMemoryCleanable = Buffer.allocateDirectBufferWithNativeOrder(total);
41          ByteBuffer msgHdrMemoryArrayMemory = msgHdrMemoryArrayMemoryCleanable.buffer();
42          for (int i = 0; i < hdrs.length; i++) {
43              hdrs[i] = new MsgHdrMemory((short) i, msgHdrMemoryArrayMemory);
44              ids[i] = NO_ID;
45          }
46      }
47  
48      boolean isFull() {
49          return idx == hdrs.length;
50      }
51  
52      MsgHdrMemory nextHdr() {
53          if (isFull()) {
54              return null;
55          }
56          return hdrs[idx++];
57      }
58  
59      void restoreNextHdr(MsgHdrMemory hdr) {
60          assert hdr.idx() == idx - 1;
61          idx--;
62      }
63  
64      MsgHdrMemory hdr(int idx) {
65          return hdrs[idx];
66      }
67  
68      long id(int idx) {
69          return ids[idx];
70      }
71  
72      void setId(int idx, long id) {
73          ids[idx] = id;
74      }
75  
76      void clear() {
77          Arrays.fill(ids, 0, idx, NO_ID);
78          idx = 0;
79      }
80  
81      int length() {
82          return idx;
83      }
84  
85      void release() {
86          assert !released;
87          released = true;
88          for (MsgHdrMemory hdr: hdrs) {
89              hdr.release();
90          }
91          msgHdrMemoryArrayMemoryCleanable.clean();
92      }
93  
94      int capacity() {
95          return capacity;
96      }
97  }