~moody/ninep

ref: 7b4c0484154111591a670ce6807bfbda3e864f36 ninep/util.go -rw-r--r-- 1.1 KiB
7b4c0484 — Jacob Moody More docs touchup 2 months ago
                                                                                
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
package ninep

import "encoding/binary"

func putStr(b []byte, s string) int {
	l := len(s)
	binary.LittleEndian.PutUint16(b, uint16(l))
	copy(b[2:], s)
	return l + 2
}

func getStr(b []byte) (int, string) {
	size := binary.LittleEndian.Uint16(b)
	return int(size) + 2, string(b[2 : 2+size])
}

//ReadBuf is a helper function that
//takes the offset and count specified
//within the Tread requests and uses
//them to slice b and respond.
func ReadBuf(t *Tread, b []byte) {
	count := int(t.Count)
	off := int(t.Offset)
	if off >= len(b) {
		t.Respond(&Rread{Data: []byte{}}, nil)
		return
	}
	if off+count > len(b) {
		count = len(b) - off
	}
	t.Respond(&Rread{Data: b[off : off+count]}, nil)
}

//ReadDir is a helper function that
//is used to respond to Tread messages
//on directories. The dirs slice should
//contain all of the files within the
//directory.
func ReadDir(t *Tread, dirs []Dir) {
	//This sucks
	size := 0
	for _, d := range dirs {
		size += d.size()
	}
	b := make([]byte, size)
	n := 0
	for _, d := range dirs {
		d.encode(b[n:])
		n += d.size()
	}
	ReadBuf(t, b)
}