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) { | |
17 funnybase.WriteUint(buf, uint64(len(s))) | |
18 buf.WriteString(s) | |
Vadim Sh.
2015/05/24 19:43:26
writeBytes(buf, []byte(s))
to be symmetric with r
iannucci
2015/05/24 20:33:54
I did this to avoid a copy (which I think is what
| |
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) | |
Vadim Sh.
2015/05/24 19:43:26
I don't fully understand yet where this function i
iannucci
2015/05/24 20:33:54
Good idea. It can actually be 2MB I think (since i
| |
36 if err != nil { | |
37 return nil, err | |
38 } | |
39 retBuf := make([]byte, val) | |
40 n, _ := buf.Read(retBuf) // err is either io.EOF or nil for bytes.Buffer | |
41 if uint64(n) != val { | |
42 return nil, fmt.Errorf("readBytes: expected %d bytes but read %d ", val, n) | |
43 } | |
44 return retBuf, err | |
45 } | |
46 | |
47 func writeFloat64(buf *bytes.Buffer, v float64) { | |
48 // byte-ordered floats http://stereopsis.com/radix.html | |
49 bits := math.Float64bits(v) | |
50 bits = bits ^ (-(bits >> 63) | (1 << 63)) | |
51 data := make([]byte, 8) | |
52 binary.BigEndian.PutUint64(data, bits) | |
53 buf.Write(data) | |
54 } | |
55 | |
56 func readFloat64(buf *bytes.Buffer) (float64, error) { | |
57 // byte-ordered floats http://stereopsis.com/radix.html | |
58 data := make([]byte, 8) | |
59 _, err := buf.Read(data) | |
60 if err != nil { | |
61 return 0, err | |
62 } | |
63 bits := binary.BigEndian.Uint64(data) | |
64 return math.Float64frombits(bits ^ (((bits >> 63) - 1) | (1 << 63))), ni l | |
65 } | |
66 | |
67 func btoi(b bool) byte { | |
68 if b { | |
69 return 1 | |
70 } | |
71 return 0 | |
72 } | |
73 | |
74 func itob(v byte) bool { | |
75 if v != 0 { | |
76 return true | |
77 } | |
78 return false | |
79 } | |
OLD | NEW |