]> git.r.bdr.sh - rbdr/mobius/blob - hotline/file_path.go
Tests and minor fixes
[rbdr/mobius] / hotline / file_path.go
1 package hotline
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "path"
8 )
9
10 const 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"
16 type FilePathItem struct {
17 Len byte
18 Name []byte
19 }
20
21 func NewFilePathItem(b []byte) FilePathItem {
22 return FilePathItem{
23 Len: b[2],
24 Name: b[3:],
25 }
26 }
27
28 type FilePath struct {
29 ItemCount [2]byte
30 Items []FilePathItem
31 }
32
33 const minFilePathLen = 2
34 func (fp *FilePath) UnmarshalBinary(b []byte) error {
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 }
42
43 pathData := b[2:]
44 for i := uint16(0); i < fp.Len(); i++ {
45 segLen := pathData[2]
46 fp.Items = append(fp.Items, NewFilePathItem(pathData[:segLen+3]))
47 pathData = pathData[3+segLen:]
48 }
49
50 return nil
51 }
52
53 func (fp *FilePath) Len() uint16 {
54 return binary.BigEndian.Uint16(fp.ItemCount[:])
55 }
56
57 func (fp *FilePath) String() string {
58 out := []string{"/"}
59 for _, i := range fp.Items {
60 out = append(out, string(i.Name))
61 }
62
63 return path.Join(out...)
64 }
65
66 func 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 }