OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 package memory | |
6 | |
7 import ( | |
8 "bytes" | |
9 "encoding/binary" | |
10 "fmt" | |
11 "math" | |
12 | |
13 "github.com/luci/luci-go/common/funnybase" | |
14 ) | |
15 | |
16 func writeString(buf *bytes.Buffer, s string) { | |
M-A Ruel
2015/05/27 20:14:47
Why not a io.Writer? I'd be much more idiomatic.
iannucci
2015/05/27 21:36:22
because io.Writer.Write returns an error... since
| |
17 funnybase.WriteUint(buf, uint64(len(s))) | |
18 buf.WriteString(s) | |
19 } | |
20 | |
21 func readString(buf *bytes.Buffer) (string, error) { | |
22 b, err := readBytes(buf) | |
23 if err != nil { | |
24 return "", err | |
25 } | |
26 return string(b), nil | |
27 } | |
28 | |
29 func writeBytes(buf *bytes.Buffer, b []byte) { | |
30 funnybase.WriteUint(buf, uint64(len(b))) | |
31 buf.Write(b) | |
32 } | |
33 | |
34 func readBytes(buf *bytes.Buffer) ([]byte, error) { | |
35 val, err := funnybase.ReadUint(buf) | |
36 if err != nil { | |
37 return nil, err | |
38 } | |
39 if val > 2*1024*1024 { // 2MB | |
40 return nil, fmt.Errorf("readBytes: tried to read %d bytes (> 2MB )", val) | |
41 } | |
42 retBuf := make([]byte, val) | |
43 n, _ := buf.Read(retBuf) // err is either io.EOF or nil for bytes.Buffer | |
44 if uint64(n) != val { | |
45 return nil, fmt.Errorf("readBytes: expected %d bytes but read %d ", val, n) | |
46 } | |
47 return retBuf, err | |
48 } | |
49 | |
50 func writeFloat64(buf *bytes.Buffer, v float64) { | |
51 // byte-ordered floats http://stereopsis.com/radix.html | |
52 bits := math.Float64bits(v) | |
53 bits = bits ^ (-(bits >> 63) | (1 << 63)) | |
54 data := make([]byte, 8) | |
55 binary.BigEndian.PutUint64(data, bits) | |
56 buf.Write(data) | |
57 } | |
58 | |
59 func readFloat64(buf *bytes.Buffer) (float64, error) { | |
60 // byte-ordered floats http://stereopsis.com/radix.html | |
61 data := make([]byte, 8) | |
62 _, err := buf.Read(data) | |
63 if err != nil { | |
64 return 0, err | |
65 } | |
66 bits := binary.BigEndian.Uint64(data) | |
67 return math.Float64frombits(bits ^ (((bits >> 63) - 1) | (1 << 63))), ni l | |
68 } | |
69 | |
70 func btoi(b bool) byte { | |
71 if b { | |
72 return 1 | |
73 } | |
74 return 0 | |
75 } | |
OLD | NEW |