xref: /aosp_15_r20/external/tink/cc/util/buffer.h (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 
17 #ifndef TINK_UTIL_BUFFER_H_
18 #define TINK_UTIL_BUFFER_H_
19 
20 #include <memory>
21 
22 #include "absl/memory/memory.h"
23 #include "tink/util/status.h"
24 #include "tink/util/statusor.h"
25 
26 namespace crypto {
27 namespace tink {
28 namespace util {
29 
30 class Buffer {
31  public:
32   // Creates a new Buffer which allocates a new memory block
33   // of size 'allocated_size' and uses it for the actual data.
34   // The allocated memory block is owned by this Buffer.
35   static util::StatusOr<std::unique_ptr<Buffer>> New(int allocated_size);
36 
37   // Creates a new Buffer which uses the given 'mem_block' as a buffer
38   // for the actual data.
39   // Does NOT take the ownership of 'mem_block' which must be non-null,
40   // must allocate at least 'allocated_size' bytes, and must remain alive
41   // as long as the returned Buffer is in use.
42   static util::StatusOr<std::unique_ptr<Buffer>> NewNonOwning(
43       char* mem_block, int allocated_size);
44 
45   // Returns the internal memory block of this Buffer,
46   // that holds the actual data.
47   // A reading caller may read up to size() bytes from the block.
48   // A writing caller may write up to allocated_size() bytes to the block,
49   // and should accordingly adjust size via set_size(int).
50   virtual char* const get_mem_block() const = 0;
51 
52   // Returns the allocated size of this buffer.
53   virtual int allocated_size() const = 0;
54 
55   // Returns the current size of this buffer.
56   virtual int size() const = 0;
57 
58   // Sets the size of this buffer to 'new_size', which must
59   // be in range 0..allocated_size().
60   // Returns OK iff 0 <= new_size <= allocated_size();
61   virtual util::Status set_size(int new_size) = 0;
62 
63   virtual ~Buffer() = default;
64 };
65 
66 }  // namespace util
67 }  // namespace tink
68 }  // namespace crypto
69 
70 #endif  // TINK_UTIL_BUFFER_H_
71