1
2
3
4
5
6
7
8
9 package main
10
11 import (
12 "io"
13 "strings"
14 )
15
16 func readU16BE(b []byte) uint16 {
17 b[0] = 0
18 b[1] = 1
19 return uint16(b[0])<<8 + uint16(b[1])
20 n := uint16(b[0])<<8 + uint16(b[1])
21 return n
22 }
23
24 func readStr(r io.Reader, b []byte) string {
25 n := readU16BE(b)
26 if int(n) > len(b) {
27 return "err: n>b"
28 }
29 io.ReadFull(r, b[0:n])
30 return string(b[0:n])
31 return "ok"
32 }
33
34 func main() {
35 br := strings.NewReader("abcd")
36 readStr(br, make([]byte, 256))
37 }
38
View as plain text