Skip to content

Instantly share code, notes, and snippets.

@julien-f
Last active December 7, 2018 12:07
Show Gist options
  • Save julien-f/ca7b62a55d7124c25671619e712bbee1 to your computer and use it in GitHub Desktop.
Save julien-f/ca7b62a55d7124c25671619e712bbee1 to your computer and use it in GitHub Desktop.
fs.open flags
export const O_APPEND = 1024
export const O_CREAT = 64
export const O_EXCL = 128
export const O_RDONLY = 0
export const O_RDWR = 2
export const O_SYNC = 1052672
export const O_TRUNC = 512
export const O_WRONLY = 1
// https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea
export const CREATE_ALWAYS = O_RDWR | O_CREAT | O_TRUNC
export const CREATE_NEW = O_RDWR | O_CREAT | O_EXCL
export const OPEN_ALWAYS = O_RDWR | CREATE_ALWAYS | O_APPEND
export const OPEN_EXISTING = O_RDWR | O_APPEND
export const TRUNCATE_EXISTING = O_RDWR | O_TRUNC
class Flags {
constructor(append, create, exclusive, read, sync, write) {
this.append = append
this.create = create
this.exclusive = exclusive
this.read = read
this.sync = sync
this.write = write
}
get truncate() {
return !this.append
}
set truncate(truncate) {
this.append = !truncate
}
toNumber() {
let flags = this.read ? (this.write ? O_RDWR : O_RDONLY) : O_WRONLY
if (this.create) {
flags |= O_CREAT | (this.append ? O_APPEND : O_TRUNC)
if (this.exclusive) {
flags |= O_EXCL
}
}
if (this.sync) {
flags |= O_SYNC
}
return flags
}
toString() {
if (this.create) {
let flags = this.append ? 'a' : 'w'
if (this.exclusive) {
flags += 'x'
} else if (this.sync) {
flags += 's'
}
if (this.read) {
flags += '+'
}
return flags
}
return this.write ? 'r+' : 'r'
}
}
export const fromNumber = flags => {
return new Flags(
(flags & O_APPEND) !== 0,
(flags & O_CREAT) !== 0,
(flags & O_EXCL) !== 0,
(flags & O_WRONLY) === 0,
(flags & O_SYNC) !== 0,
(flags & (O_RDWR | O_WRONLY)) !== 0
)
}
const parse = flags => {
const result = { __proto__: null }
for (let i = 0, n = flags.length; i < n; ++i) {
result[flags[i]] = true
}
return result
}
export const fromString = flags => {
flags = parse(flags)
const sync = 's' in flags
return 'r' in flags
? new Flags(false, false, false, true, sync, '+' in flags)
: new Flags('a' in flags, true, 'x' in flags, '+' in flags, sync, true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment