github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/storage/dimension/serialization.go (about) 1 package dimension 2 3 import ( 4 "bufio" 5 "bytes" 6 "io" 7 8 "github.com/pyroscope-io/pyroscope/pkg/util/varint" 9 ) 10 11 // serialization format version. it's not very useful right now, but it will be in the future 12 const currentVersion = 1 13 14 func (s *Dimension) Serialize(w io.Writer) error { 15 s.m.RLock() 16 defer s.m.RUnlock() 17 18 _, err := varint.Write(w, currentVersion) 19 if err != nil { 20 return err 21 } 22 23 for _, k := range s.Keys { 24 _, err = varint.Write(w, uint64(len(k))) 25 if err != nil { 26 return err 27 } 28 _, err = w.Write(k) 29 if err != nil { 30 return err 31 } 32 } 33 return nil 34 } 35 36 func Deserialize(r io.Reader) (*Dimension, error) { 37 s := New() 38 39 br := bufio.NewReader(r) // TODO if it's already a bytereader skip 40 41 // reads serialization format version, see comment at the top 42 _, err := varint.Read(br) 43 if err != nil { 44 return nil, err 45 } 46 47 for { 48 keyLen, err := varint.Read(br) 49 if err != nil { 50 if err == io.EOF { 51 break 52 } 53 return nil, err 54 } 55 keyBuf := make([]byte, keyLen) // TODO: there are better ways to do this? 56 _, err = io.ReadAtLeast(br, keyBuf, int(keyLen)) 57 if err != nil { 58 return nil, err 59 } 60 61 s.Keys = append(s.Keys, Key(keyBuf)) 62 } 63 64 return s, nil 65 } 66 67 func (s *Dimension) Bytes() ([]byte, error) { 68 b := bytes.Buffer{} 69 if err := s.Serialize(&b); err != nil { 70 return nil, err 71 } 72 return b.Bytes(), nil 73 } 74 75 func FromBytes(p []byte) (*Dimension, error) { 76 return Deserialize(bytes.NewReader(p)) 77 }