View Javadoc
1   /*
2    * Copyright 2021 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.buffer.api;
17  
18  import io.netty5.util.Send;
19  
20  import java.lang.invoke.VarHandle;
21  
22  /**
23   * A mutable reference to a buffer.
24   */
25  public final class BufferRef extends BufferHolder<BufferRef> {
26      /**
27       * Create a reference to the given {@linkplain Buffer buffer}.
28       *
29       * @param buf The buffer to reference.
30       */
31      private BufferRef(Buffer buf) {
32          super(buf);
33          // BufferRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store.
34          VarHandle.fullFence();
35      }
36  
37      /**
38       * Create a reference that holds the exclusive ownership of the sent buffer.
39       *
40       * @param send The {@linkplain Send sent} buffer to take ownership of.
41       */
42      public BufferRef(Send<Buffer> send) {
43          super(send);
44          // BufferRef is meant to be atomic, so we need to add a fence to get the semantics of a volatile store.
45          VarHandle.fullFence();
46      }
47  
48      @Override
49      protected BufferRef receive(Buffer buf) {
50          return new BufferRef(buf);
51      }
52  
53      /**
54       * Replace the underlying referenced buffer with the given buffer.
55       * <p>
56       * <strong>Note:</strong> this method closes the current buffer,
57       * and takes exclusive ownership of the received buffer.
58       * <p>
59       * The buffer assignment is performed using a volatile store.
60       *
61       * @param send The {@link Send} with the new {@link Buffer} instance that is replacing the currently held buffer.
62       */
63      public void replace(Send<Buffer> send) {
64          replaceBufferVolatile(send);
65      }
66  
67      /**
68       * Access the buffer in this reference.
69       *
70       * @return The buffer held by the reference.
71       */
72      public Buffer content() {
73          return getBufferVolatile();
74      }
75  }