xref: /aosp_15_r20/system/core/fs_mgr/libsnapshot/snapuserd/include/snapuserd/snapuserd_buffer.h (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 // Copyright (C) 2021 The Android Open Source Project
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 #pragma once
16 
17 #include <linux/types.h>
18 #include <stdint.h>
19 #include <stdlib.h>
20 
21 #include <iostream>
22 
23 #include <libsnapshot/cow_reader.h>
24 
25 namespace android {
26 namespace snapshot {
27 
28 class BufferSink final {
29   public:
30     // Do not reserve any space of header by default
Initialize(size_t size)31     void Initialize(size_t size) { return Initialize(0, size); };
32     // This allows to set const header_size_ to be used if caller needs it
33     // for example, while working with dm_user
34     void Initialize(size_t header_size, size_t size);
GetBufPtr()35     void* GetBufPtr() { return buffer_.get(); }
Clear()36     void Clear() { memset(GetBufPtr(), 0, buffer_size_); }
37     void* GetPayloadBuffer(size_t size);
38     void* GetBuffer(size_t requested, size_t* actual);
UpdateBufferOffset(size_t size)39     void UpdateBufferOffset(size_t size) { buffer_offset_ += size; }
40     void* GetHeaderPtr();
ResetBufferOffset()41     void ResetBufferOffset() { buffer_offset_ = 0; }
42     void* GetPayloadBufPtr();
GetPayloadBytesWritten()43     loff_t GetPayloadBytesWritten() { return buffer_offset_; }
44 
45     // Same as calling GetPayloadBuffer and then UpdateBufferOffset.
46     //
47     // This is preferred over GetPayloadBuffer as it does not require a
48     // separate call to UpdateBufferOffset.
AcquireBuffer(size_t size)49     void* AcquireBuffer(size_t size) { return AcquireBuffer(size, size); }
50 
51     // Same as AcquireBuffer, but separates the requested size from the buffer
52     // offset. This is useful for a situation where a full run of data will be
53     // read, but only a partial amount will be returned.
54     //
55     // If size != to_write, the excess bytes may be reallocated by the next
56     // call to AcquireBuffer.
57     void* AcquireBuffer(size_t size, size_t to_write);
58 
59   private:
60     std::unique_ptr<uint8_t[]> buffer_;
61     loff_t buffer_offset_;
62     size_t buffer_size_;
63     size_t header_size_;
64 };
65 
66 }  // namespace snapshot
67 }  // namespace android
68