diff --git a/container/container.go b/container/container.go index 70f62de..d85423b 100644 --- a/container/container.go +++ b/container/container.go @@ -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() diff --git a/container/serialization.go b/container/serialization.go new file mode 100644 index 0000000..d996c74 --- /dev/null +++ b/container/serialization.go @@ -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 +}