-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpos.go
54 lines (49 loc) · 926 Bytes
/
pos.go
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
package ybase
import (
"encoding/json"
"fmt"
)
type (
Pos interface {
Line() int
Column() int
Offset() int
Add(r rune) Pos
}
pos struct {
line, col, offset int
}
)
func NewPos(line, col, offset int) Pos {
return &pos{
line: line,
col: col,
offset: offset,
}
}
func (s pos) Line() int { return s.line }
func (s pos) Column() int { return s.col }
func (s pos) Offset() int { return s.offset }
func (s pos) String() string { return fmt.Sprintf("%d,%d,%d", s.line, s.col, s.offset) }
func (s *pos) Add(r rune) Pos {
size := len([]byte(string(r)))
if r == '\n' {
return &pos{
line: s.line + 1,
col: 0,
offset: s.offset + size,
}
}
return &pos{
line: s.line,
col: s.col + 1,
offset: s.offset + size,
}
}
func (s pos) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{
"line": s.line,
"col": s.col,
"offset": s.offset,
})
}