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