summaryrefslogtreecommitdiff
path: root/internal/file/flags.go
blob: c06c27b2f91e0968b8809aa262b25c93bda6eddf (plain)
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
package file

import (
	"os"
	"strings"
	"sync"
	"syscall"
)

type Flags int32

var flagsToHumanCache sync.Map
var unknownFlag = Flags(-1)

type tuple struct {
	syscallNr int
	str       string
}

var flagsToHuman = []tuple{
	{-1, "O_NONE"},
	{syscall.O_RDONLY, "O_RDONLY"},
	{syscall.O_WRONLY, "O_WRONLY"},
	{syscall.O_RDWR, "O_RDWR"},
	{syscall.O_ACCMODE, "O_ACCMODE"},
	{syscall.O_APPEND, "O_APPEND"},
	{syscall.O_ASYNC, "O_ASYNC"},
	{syscall.O_CLOEXEC, "O_CLOEXEC"},
	{syscall.O_CREAT, "O_CREAT"},
	{syscall.O_DIRECT, "O_DIRECT"},
	{syscall.O_DIRECTORY, "O_DIRECTORY"},
	{syscall.O_DSYNC, "O_DSYNC"},
	{syscall.O_EXCL, "O_EXCL"},
	{syscall.O_NOATIME, "O_NOATIME"},
	{syscall.O_NOCTTY, "O_NOCTTY"},
	{syscall.O_NOFOLLOW, "O_NOFOLLOW"},
	{syscall.O_NONBLOCK, "O_NONBLOCK"},
	{syscall.O_SYNC, "O_SYNC"},
	{syscall.O_TRUNC, "O_TRUNC"},
}

func (f Flags) Is(flag int) bool {
	if f == unknownFlag {
		return false
	}
	if int(f)&flag == flag {
		return true
	}
	return false
}

func (f Flags) BuildString(sb *strings.Builder) {
	if cached, ok := flagsToHumanCache.Load(f); ok {
		str, _ := cached.(string)
		sb.WriteString(str)
		return
	}
	str := f.String()
	cached, loaded := flagsToHumanCache.LoadOrStore(f, str)
	if loaded {
		str, _ = cached.(string)
	}
	sb.WriteString(str)
}

func (f Flags) String() string {
	var strs []string

	if f == -1 {
		return "O_NONE"
	}

	if int(f)&(os.O_WRONLY|os.O_RDWR) == 0 {
		// Must be read only then
		strs = append(strs, "O_RDONLY")
	}
	for _, toHuman := range flagsToHuman[2:] {
		if int(f)&toHuman.syscallNr == toHuman.syscallNr {
			strs = append(strs, toHuman.str)
		}
	}
	if len(strs) == 0 {
		strs = append(strs, "O_RDONLY")
	}

	return strings.Join(strs, "|")
}