diff options
author | Luke Shumaker <lukeshu@lukeshu.com> | 2022-07-30 02:36:25 -0600 |
---|---|---|
committer | Luke Shumaker <lukeshu@lukeshu.com> | 2022-08-17 22:50:57 -0600 |
commit | 13b65d51ffc9768464e8330fdb73b6febd7410af (patch) | |
tree | 271fe78abc75573a330353632171284ccf2ecd47 /lib/btrfs | |
parent | eb4e771e2a99edeb5cc3a1511ab611480f98255d (diff) |
json: Implement a bunch of streaming JSON encoding/decoding
Diffstat (limited to 'lib/btrfs')
-rw-r--r-- | lib/btrfs/btrfsitem/item_extentcsum.go | 34 | ||||
-rw-r--r-- | lib/btrfs/btrfssum/csum.go | 20 |
2 files changed, 54 insertions, 0 deletions
diff --git a/lib/btrfs/btrfsitem/item_extentcsum.go b/lib/btrfs/btrfsitem/item_extentcsum.go index b35d333..eedd044 100644 --- a/lib/btrfs/btrfsitem/item_extentcsum.go +++ b/lib/btrfs/btrfsitem/item_extentcsum.go @@ -5,7 +5,11 @@ package btrfsitem import ( + "encoding/hex" "fmt" + "io" + + "git.lukeshu.com/go/lowmemjson" "git.lukeshu.com/btrfs-progs-ng/lib/btrfs/btrfssum" ) @@ -43,3 +47,33 @@ func (o ExtentCSum) MarshalBinary() ([]byte, error) { } return dat, nil } + +var ( + _ lowmemjson.Encodable = ExtentCSum{} +) + +func (o ExtentCSum) EncodeJSON(w io.Writer) error { + if _, err := fmt.Fprintf(w, `{"ChecksumSize":%d,"Sums":[`, o.ChecksumSize); err != nil { + return err + } + for i, sum := range o.Sums { + if i > 0 { + if _, err := w.Write([]byte(",")); err != nil { + return err + } + } + if _, err := w.Write([]byte(`"`)); err != nil { + return err + } + if _, err := hex.NewEncoder(w).Write(sum[:o.ChecksumSize]); err != nil { + return err + } + if _, err := w.Write([]byte(`"`)); err != nil { + return err + } + } + if _, err := w.Write([]byte(`]}`)); err != nil { + return err + } + return nil +} diff --git a/lib/btrfs/btrfssum/csum.go b/lib/btrfs/btrfssum/csum.go index 8f9ac1a..c7c1f37 100644 --- a/lib/btrfs/btrfssum/csum.go +++ b/lib/btrfs/btrfssum/csum.go @@ -5,6 +5,7 @@ package btrfssum import ( + "encoding" "encoding/binary" "encoding/hex" "fmt" @@ -15,10 +16,29 @@ import ( type CSum [0x20]byte +var ( + _ fmt.Stringer = CSum{} + _ fmt.Formatter = CSum{} + _ encoding.TextMarshaler = CSum{} + _ encoding.TextUnmarshaler = (*CSum)(nil) +) + func (csum CSum) String() string { return hex.EncodeToString(csum[:]) } +func (csum CSum) MarshalText() ([]byte, error) { + var ret [len(csum) * 2]byte + hex.Encode(ret[:], csum[:]) + return ret[:], nil +} + +func (csum *CSum) UnmarshalText(text []byte) error { + *csum = CSum{} + _, err := hex.Decode(csum[:], text) + return err +} + func (csum CSum) Fmt(typ CSumType) string { return hex.EncodeToString(csum[:typ.Size()]) } |