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 API_CORE_IO_IFILE_H
17 #define API_CORE_IO_IFILE_H
18
19 #include <cstdint>
20
21 #include <base/containers/unique_ptr.h>
22 #include <base/namespace.h>
23 #include <core/namespace.h>
24
CORE_BEGIN_NAMESPACE()25 CORE_BEGIN_NAMESPACE()
26 /** @ingroup group_io_ifile */
27 /** IFile provides methods for working with files, such as reading and writing etc. */
28 class IFile {
29 public:
30 /** Enumeration for file access mode */
31 enum class Mode {
32 /** Invalid access */
33 INVALID,
34 /** Read only access */
35 READ_ONLY,
36 /** Read and write access */
37 READ_WRITE
38 };
39
40 /** Retrieves whether file can be read / written.
41 * @return Mode of the file, either read only or read / write.
42 */
43 virtual Mode GetMode() const = 0;
44
45 /** Close the file. */
46 virtual void Close() = 0;
47
48 /** Read a sequence of bytes from file.
49 * @param buffer Buffer that retrieves data from file.
50 * @param count Number of bytes to read.
51 * @return Total number of bytes read.
52 */
53 virtual uint64_t Read(void* buffer, uint64_t count) = 0;
54
55 /** Write a sequence of bytes to file.
56 * @param buffer Buffer that contains the data to be written.
57 * @param count Number of bytes to write.
58 * @return Total number of bytes written.
59 */
60 virtual uint64_t Write(const void* buffer, uint64_t count) = 0;
61
62 /** Gets the total length of the file.
63 * @return Total length of the file in bytes.
64 */
65 virtual uint64_t GetLength() const = 0;
66
67 /** Seeks to given offset in file data.
68 * @param offset Target offset in bytes.
69 * @return True if the seek was successful, otherwise false.
70 */
71 virtual bool Seek(uint64_t offset) = 0;
72
73 /** Returns the current offset in file data.
74 * @return Current offset in bytes.
75 */
76 virtual uint64_t GetPosition() const = 0;
77
78 struct Deleter {
79 constexpr Deleter() noexcept = default;
80 void operator()(IFile* ptr) const
81 {
82 ptr->Destroy();
83 }
84 };
85 using Ptr = BASE_NS::unique_ptr<IFile, Deleter>;
86
87 protected:
88 IFile() = default;
89 virtual ~IFile() = default;
90 virtual void Destroy() = 0;
91 };
92 CORE_END_NAMESPACE()
93
94 #endif // API_CORE_IO_IFILE_H
95