mirror of
https://github.com/safing/portbase
synced 2025-09-01 10:09:50 +00:00
Add WriteAllTo method and container serialization
This commit is contained in:
parent
146b6724cc
commit
94cbc1fa8d
2 changed files with 37 additions and 0 deletions
|
@ -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()
|
||||
|
|
21
container/serialization.go
Normal file
21
container/serialization.go
Normal 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
|
||||
}
|
Loading…
Add table
Reference in a new issue