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 #include "io/memory_file.h"
17
18 #include <cstdint>
19 #include <cstring>
20 #include <memory>
21
22 #include <base/containers/allocator.h>
23 #include <base/containers/vector.h>
24 #include <base/namespace.h>
25 #include <core/io/intf_file.h>
26 #include <core/log.h>
27 #include <core/namespace.h>
28
29 CORE_BEGIN_NAMESPACE()
30 using BASE_NS::CloneData;
31
Write(uint64_t index,const void * buffer,uint64_t count)32 uint64_t MemoryFileStorage::Write(uint64_t index, const void* buffer, uint64_t count)
33 {
34 if (index >= buffer_.size()) {
35 return 0;
36 }
37 if (CloneData(buffer_.data() + index, buffer_.size() - index, buffer, static_cast<size_t>(count))) {
38 return count;
39 }
40 return 0;
41 }
42
MemoryFile(std::shared_ptr<MemoryFileStorage> && buffer)43 MemoryFile::MemoryFile(std::shared_ptr<MemoryFileStorage>&& buffer) : buffer_(move(buffer)) {}
44
GetMode() const45 IFile::Mode MemoryFile::GetMode() const
46 {
47 return IFile::Mode::READ_ONLY;
48 }
49
Close()50 void MemoryFile::Close() {}
51
Read(void * buffer,uint64_t count)52 uint64_t MemoryFile::Read(void* buffer, uint64_t count)
53 {
54 uint64_t toRead = count;
55 if ((index_ + toRead) > buffer_->GetStorage().size()) {
56 toRead = buffer_->GetStorage().size() - index_;
57 }
58
59 if (toRead > 0) {
60 if (toRead <= SIZE_MAX) {
61 if (CloneData(buffer, static_cast<size_t>(count), &(buffer_->GetStorage().data()[index_]),
62 static_cast<size_t>(toRead))) {
63 index_ += toRead;
64 }
65 } else {
66 CORE_ASSERT_MSG(false, "Unable to read chunks bigger than (SIZE_MAX) bytes.");
67 toRead = 0;
68 }
69 }
70
71 return toRead;
72 }
73
Write(const void * buffer,uint64_t count)74 uint64_t MemoryFile::Write(const void* buffer, uint64_t count)
75 {
76 buffer_->Resize(size_t(count));
77 return buffer_->Write(0, buffer, count);
78 }
79
GetLength() const80 uint64_t MemoryFile::GetLength() const
81 {
82 return buffer_->GetStorage().size();
83 }
84
Seek(uint64_t aOffset)85 bool MemoryFile::Seek(uint64_t aOffset)
86 {
87 if (aOffset < buffer_->GetStorage().size()) {
88 index_ = aOffset;
89 return true;
90 }
91
92 return false;
93 }
94
GetPosition() const95 uint64_t MemoryFile::GetPosition() const
96 {
97 return index_;
98 }
99 CORE_END_NAMESPACE()
100