• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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 #ifndef CORE_IO_MEMORY_FILE_H
17 #define CORE_IO_MEMORY_FILE_H
18 
19 #include <cstddef>
20 #include <cstdint>
21 #include <memory>
22 
23 #include <base/containers/type_traits.h>
24 #include <base/containers/vector.h>
25 #include <base/namespace.h>
26 #include <core/io/intf_file.h>
27 #include <core/namespace.h>
28 
29 CORE_BEGIN_NAMESPACE()
30 using ByteBuffer = BASE_NS::vector<uint8_t>;
31 
32 class MemoryFileStorage {
33 public:
34     MemoryFileStorage() = default;
35     ~MemoryFileStorage() = default;
MemoryFileStorage(ByteBuffer && buffer)36     explicit MemoryFileStorage(ByteBuffer&& buffer) : buffer_(BASE_NS::move(buffer)) {}
37 
GetStorage()38     const ByteBuffer& GetStorage() const
39     {
40         return buffer_;
41     }
42 
Size()43     uint64_t Size() const
44     {
45         return static_cast<uint64_t>(buffer_.size());
46     }
47 
Resize(size_t newSize)48     void Resize(size_t newSize)
49     {
50         buffer_.resize(newSize);
51     }
52 
53     uint64_t Write(uint64_t index, const void* buffer, uint64_t count);
54 
55 private:
56     ByteBuffer buffer_;
57 };
58 
59 /** Read-only memory file. */
60 class MemoryFile final : public IFile {
61 public:
62     MemoryFile(std::shared_ptr<MemoryFileStorage>&& buffer, Mode mode);
63 
64     ~MemoryFile() override = default;
65 
66     Mode GetMode() const override;
67 
68     void Close() override;
69 
70     uint64_t Read(void* buffer, uint64_t count) override;
71 
72     uint64_t Write(const void* buffer, uint64_t count) override;
73 
74     uint64_t Append(const void* buffer, uint64_t count, uint64_t chunkSize) override;
75 
76     uint64_t GetLength() const override;
77 
78     bool Seek(uint64_t offset) override;
79 
80     uint64_t GetPosition() const override;
81 
82 protected:
Destroy()83     void Destroy() override
84     {
85         delete this;
86     }
87 
88 private:
89     uint64_t index_ { 0 };
90     std::shared_ptr<MemoryFileStorage> buffer_;
91     Mode mode_ { Mode::INVALID };
92 };
93 CORE_END_NAMESPACE()
94 
95 #endif // CORE_IO_MEMORY_FILE_H
96