]> git.r.bdr.sh - rbdr/mobius/blame - hotline/file_path.go
Tests and minor fixes
[rbdr/mobius] / hotline / file_path.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
00d1ef67 4 "bytes"
6988a057 5 "encoding/binary"
00d1ef67
JH
6 "errors"
7 "path"
6988a057
JH
8)
9
10const pathSeparator = "/" // File path separator TODO: make configurable to support Windows
11
12// FilePathItem represents the file or directory portion of a delimited file path (e.g. foo and bar in "/foo/bar")
13// 00 00
14// 09
15// 73 75 62 66 6f 6c 64 65 72 // "subfolder"
16type FilePathItem struct {
17 Len byte
18 Name []byte
19}
20
21func NewFilePathItem(b []byte) FilePathItem {
22 return FilePathItem{
23 Len: b[2],
24 Name: b[3:],
25 }
26}
27
28type FilePath struct {
00d1ef67 29 ItemCount [2]byte
72dd37f1 30 Items []FilePathItem
6988a057
JH
31}
32
00d1ef67 33const minFilePathLen = 2
72dd37f1 34func (fp *FilePath) UnmarshalBinary(b []byte) error {
00d1ef67
JH
35 if len(b) < minFilePathLen {
36 return errors.New("insufficient bytes")
37 }
38 err := binary.Read(bytes.NewReader(b[0:2]), binary.BigEndian, &fp.ItemCount)
39 if err != nil {
40 return err
41 }
6988a057 42
6988a057 43 pathData := b[2:]
72dd37f1 44 for i := uint16(0); i < fp.Len(); i++ {
6988a057 45 segLen := pathData[2]
72dd37f1 46 fp.Items = append(fp.Items, NewFilePathItem(pathData[:segLen+3]))
6988a057
JH
47 pathData = pathData[3+segLen:]
48 }
49
72dd37f1
JH
50 return nil
51}
52
53func (fp *FilePath) Len() uint16 {
00d1ef67 54 return binary.BigEndian.Uint16(fp.ItemCount[:])
6988a057
JH
55}
56
57func (fp *FilePath) String() string {
00d1ef67 58 out := []string{"/"}
72dd37f1 59 for _, i := range fp.Items {
6988a057
JH
60 out = append(out, string(i.Name))
61 }
00d1ef67
JH
62
63 return path.Join(out...)
6988a057 64}
c5d9af5a
JH
65
66func ReadFilePath(filePathFieldData []byte) string {
67 var fp FilePath
68 err := fp.UnmarshalBinary(filePathFieldData)
69 if err != nil {
70 // TODO
71 }
72 return fp.String()
73}