• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 package com.google.protobuf;
9 
10 import java.nio.ByteBuffer;
11 
12 /**
13  * An object responsible for allocation of buffers. This is an extension point to enable buffer
14  * pooling within an application.
15  */
16 @CheckReturnValue
17 @ExperimentalApi
18 abstract class BufferAllocator {
19   private static final BufferAllocator UNPOOLED =
20       new BufferAllocator() {
21         @Override
22         public AllocatedBuffer allocateHeapBuffer(int capacity) {
23           return AllocatedBuffer.wrap(new byte[capacity]);
24         }
25 
26         @Override
27         public AllocatedBuffer allocateDirectBuffer(int capacity) {
28           return AllocatedBuffer.wrap(ByteBuffer.allocateDirect(capacity));
29         }
30       };
31 
32   /** Returns an unpooled buffer allocator, which will create a new buffer for each request. */
unpooled()33   public static BufferAllocator unpooled() {
34     return UNPOOLED;
35   }
36 
37   /** Allocates a buffer with the given capacity that is backed by an array on the heap. */
allocateHeapBuffer(int capacity)38   public abstract AllocatedBuffer allocateHeapBuffer(int capacity);
39 
40   /** Allocates a direct (i.e. non-heap) buffer with the given capacity. */
allocateDirectBuffer(int capacity)41   public abstract AllocatedBuffer allocateDirectBuffer(int capacity);
42 }
43