SimpleKernel 1.17.0
Loading...
Searching...
No Matches
seek.cpp
Go to the documentation of this file.
1
5#include "filesystem.hpp"
6#include "kernel_log.hpp"
7#include "kstd_cstring"
8#include "spinlock.hpp"
9#include "vfs_internal.hpp"
10
11namespace vfs {
12
13auto Seek(File* file, int64_t offset, SeekWhence whence) -> Expected<uint64_t> {
14 if (file == nullptr) {
15 return std::unexpected(Error(ErrorCode::kInvalidArgument));
16 }
17
18 LockGuard<SpinLock> guard(GetVfsState().vfs_lock_);
19 if (file->ops != nullptr) {
20 return file->ops->Seek(file, offset, whence);
21 }
22
23 // 默认实现
24 uint64_t new_offset = file->offset;
25
26 switch (whence) {
28 if (offset < 0) {
29 return std::unexpected(Error(ErrorCode::kInvalidArgument));
30 }
31 new_offset = static_cast<uint64_t>(offset);
32 break;
34 if (offset < 0 && static_cast<uint64_t>(-offset) > file->offset) {
35 return std::unexpected(Error(ErrorCode::kInvalidArgument));
36 }
37 new_offset =
38 static_cast<uint64_t>(static_cast<int64_t>(file->offset) + offset);
39 break;
41 if (file->inode == nullptr) {
42 return std::unexpected(Error(ErrorCode::kFsCorrupted));
43 }
44 if (offset < 0 && static_cast<uint64_t>(-offset) > file->inode->size) {
45 return std::unexpected(Error(ErrorCode::kInvalidArgument));
46 }
47 new_offset = static_cast<uint64_t>(
48 static_cast<int64_t>(file->inode->size) + offset);
49 break;
50 default:
51 return std::unexpected(Error(ErrorCode::kInvalidArgument));
52 }
53
54 file->offset = new_offset;
55 return new_offset;
56}
57
58} // namespace vfs
RAII 风格的锁守卫模板类
Definition spinlock.hpp:131
@ kInvalidArgument
std::expected< T, Error > Expected
std::expected 别名模板
Definition expected.hpp:365
auto GetVfsState() -> VfsState &
Definition vfs.cpp:17
auto Seek(File *file, int64_t offset, SeekWhence whence) -> Expected< uint64_t >
调整文件偏移量
Definition seek.cpp:13
SeekWhence
文件 seek 基准
Definition vfs_types.hpp:94
@ kSet
从文件开头
@ kCur
从当前位置
@ kEnd
从文件末尾
错误类型,用于 std::expected
Definition expected.hpp:343
File — 打开的文件实例(每次 open 产生一个)
Definition vfs.hpp:65