Add WriteAllTo method and container serialization

This commit is contained in:
Daniel 2020-01-12 20:53:48 +01:00
parent 146b6724cc
commit 94cbc1fa8d
2 changed files with 37 additions and 0 deletions

View file

@ -2,6 +2,7 @@ package container
import (
"errors"
"io"
"github.com/safing/portbase/formats/varint"
)
@ -146,6 +147,21 @@ func (c *Container) WriteToSlice(slice []byte) (n int, containerEmptied bool) {
return n, true
}
// WriteAllTo writes all the data to the given io.Writer. Data IS NOT copied (but may be by writer) and IS NOT consumed.
func (c *Container) WriteAllTo(writer io.Writer) error {
for i := c.offset; i < len(c.compartments); i++ {
written := 0
for written < len(c.compartments[i]) {
n, err := writer.Write(c.compartments[i][written:])
if err != nil {
return err
}
written += n
}
}
return nil
}
func (c *Container) clean() {
if c.offset > 100 {
c.renewCompartments()

View file

@ -0,0 +1,21 @@
package container
import (
"encoding/json"
)
// MarshalJSON serializes the container as a JSON byte array.
func (c *Container) MarshalJSON() ([]byte, error) {
return json.Marshal(c.CompileData())
}
// UnmarshalJSON unserializes a container from a JSON byte array.
func (c *Container) UnmarshalJSON(data []byte) error {
var raw []byte
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
c.compartments = [][]byte{raw}
return nil
}