forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfd.js
More file actions
87 lines (76 loc) · 1.76 KB
/
fd.js
File metadata and controls
87 lines (76 loc) · 1.76 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
78
79
80
81
82
83
84
85
86
87
'use strict';
const {
SafeMap,
Symbol,
} = primordials;
// Private symbols
const kFd = Symbol('kFd');
const kEntry = Symbol('kEntry');
// VFS FDs use bit 30 set to avoid conflicts with real OS fds.
// Real fds are small non-negative integers; VFS fds start at 0x40000000.
const VFS_FD_MASK = 0x40000000;
let nextFd = 0;
// Global registry of open virtual file descriptors
const openFDs = new SafeMap();
/**
* Represents an open virtual file descriptor.
* Wraps a VirtualFileHandle from the provider.
*/
class VirtualFD {
/**
* @param {number} fd The file descriptor number
* @param {VirtualFileHandle} entry The virtual file handle
*/
constructor(fd, entry) {
this[kFd] = fd;
this[kEntry] = entry;
}
/**
* Gets the file descriptor number.
* @returns {number}
*/
get fd() {
return this[kFd];
}
/**
* Gets the file handle.
* @returns {VirtualFileHandle}
*/
get entry() {
return this[kEntry];
}
}
/**
* Opens a virtual file and returns its file descriptor.
* @param {VirtualFileHandle} entry The virtual file handle
* @returns {number} The file descriptor
*/
function openVirtualFd(entry) {
const fd = VFS_FD_MASK | nextFd++;
const vfd = new VirtualFD(fd, entry);
openFDs.set(fd, vfd);
return fd;
}
/**
* Gets a VirtualFD by its file descriptor number.
* @param {number} fd The file descriptor number
* @returns {VirtualFD|undefined}
*/
function getVirtualFd(fd) {
return openFDs.get(fd);
}
/**
* Closes a virtual file descriptor.
* @param {number} fd The file descriptor number
* @returns {boolean} True if the fd was found and closed
*/
function closeVirtualFd(fd) {
return openFDs.delete(fd);
}
module.exports = {
VFS_FD_MASK,
VirtualFD,
openVirtualFd,
getVirtualFd,
closeVirtualFd,
};