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