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 #ifndef META_SRC_RESOURCE_MEMFILE_HEADER 16 #define META_SRC_RESOURCE_MEMFILE_HEADER 17 18 #include <algorithm> 19 #include <cstring> 20 #include <securec.h> 21 22 #include <base/containers/vector.h> 23 #include <core/io/intf_file.h> 24 #include <core/log.h> 25 26 META_BEGIN_NAMESPACE() 27 28 struct MemFile : public CORE_NS::IFile { data_MemFile29 explicit MemFile(BASE_NS::vector<uint8_t> vec = {}) : data_(BASE_NS::move(vec)) {} 30 GetModeMemFile31 Mode GetMode() const override 32 { 33 return Mode::READ_WRITE; 34 } CloseMemFile35 void Close() override 36 { 37 data_.clear(); 38 } ReadMemFile39 uint64_t Read(void* buffer, uint64_t count) override 40 { 41 size_t read = std::min<size_t>(count, data_.size() - pos_); 42 if (read) { 43 memcpy_s(buffer, read, &data_[pos_], read); 44 pos_ += read; 45 } 46 return read; 47 } WriteMemFile48 uint64_t Write(const void* buffer, uint64_t count) override 49 { 50 if (data_.size() < pos_ + count) { 51 data_.resize(pos_ + count); 52 } 53 memcpy_s(&data_[pos_], count, buffer, count); 54 pos_ += count; 55 return count; 56 } AppendMemFile57 uint64_t Append(const void* buffer, uint64_t count, uint64_t flushSize) override 58 { 59 if (data_.size() < pos_ + count) { 60 data_.resize(pos_ + count); 61 } 62 memcpy_s(&data_[pos_], count, buffer, count); 63 pos_ += count; 64 return count; 65 } GetLengthMemFile66 uint64_t GetLength() const override 67 { 68 return data_.size(); 69 } SeekMemFile70 bool Seek(uint64_t offset) override 71 { 72 bool ret = offset < data_.size(); 73 if (ret) { 74 pos_ = offset; 75 } 76 return ret; 77 } GetPositionMemFile78 uint64_t GetPosition() const override 79 { 80 return pos_; 81 } DataMemFile82 BASE_NS::vector<uint8_t> Data() const 83 { 84 return data_; 85 } RawDataMemFile86 const uint8_t* RawData() const 87 { 88 return data_.data(); 89 } 90 91 private: DestroyMemFile92 void Destroy() override 93 { 94 delete this; 95 } 96 97 BASE_NS::vector<uint8_t> data_; 98 size_t pos_ {}; 99 }; 100 101 META_END_NAMESPACE() 102 103 #endif 104