-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDescTable.cpp
More file actions
77 lines (65 loc) · 1.61 KB
/
Copy pathFileDescTable.cpp
File metadata and controls
77 lines (65 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//===-- FileDescTable.cpp - FD pool -----------------------------*- C++ -*-===//
//
// Part of the ZBC semihosting monorepo. MIT licensed (see LICENSE).
//
//===----------------------------------------------------------------------===//
#include "zbc/FileDescTable.h"
namespace zbc {
FileDescTable::FileDescTable() {
Files.fill(nullptr);
Files[0] = stdin;
Files[1] = stdout;
Files[2] = stderr;
}
FileDescTable::~FileDescTable() { closeAll(); }
FileDescTable::FileDescTable(FileDescTable &&Other) noexcept
: Files(Other.Files) {
Other.Files.fill(nullptr);
}
FileDescTable &FileDescTable::operator=(FileDescTable &&Other) noexcept {
if (this != &Other) {
closeAll();
Files = Other.Files;
Other.Files.fill(nullptr);
}
return *this;
}
int FileDescTable::allocate(std::FILE *FP) {
if (!FP)
return -1;
for (int I = FirstUserFD; I < MaxFiles; ++I) {
if (Files[I] == nullptr) {
Files[I] = FP;
return I;
}
}
return -1;
}
bool FileDescTable::release(int FD) {
if (FD < FirstUserFD || FD >= MaxFiles)
return false;
if (Files[FD] == nullptr)
return false;
std::fclose(Files[FD]);
Files[FD] = nullptr;
return true;
}
std::FILE *FileDescTable::get(int FD) const {
if (FD < 0 || FD >= MaxFiles)
return nullptr;
return Files[FD];
}
bool FileDescTable::isValid(int FD) const {
if (FD < 0 || FD >= MaxFiles)
return false;
return Files[FD] != nullptr;
}
void FileDescTable::closeAll() {
for (int I = FirstUserFD; I < MaxFiles; ++I) {
if (Files[I] != nullptr) {
std::fclose(Files[I]);
Files[I] = nullptr;
}
}
}
} // namespace zbc