Skip to content

Commit

Permalink
bytesutil updates
Browse files Browse the repository at this point in the history
  • Loading branch information
sjc5 committed Jun 20, 2024
1 parent 010e3e9 commit 16d7b8f
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions pkg/bytesutil/bytesutil.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package bytesutil

import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"fmt"
)

func Random(l int) ([]byte, error) {
Expand All @@ -20,3 +23,25 @@ func FromBase64(s string) ([]byte, error) {
func ToBase64(b []byte) string {
return base64.StdEncoding.EncodeToString(b)
}

func ToGob(src any) ([]byte, error) {
var a bytes.Buffer
enc := gob.NewEncoder(&a)
err := enc.Encode(src)
if err != nil {
return nil, fmt.Errorf("bytesutil.ToGob: failed to encode src to bytes: %w", err)
}
return a.Bytes(), nil
}

func FromGobInto(gobBytes []byte, dest any) error {
if gobBytes == nil {
return fmt.Errorf("bytesutil.FromGobInto: cannot decode nil bytes")
}
dec := gob.NewDecoder(bytes.NewReader(gobBytes))
err := dec.Decode(dest)
if err != nil {
return fmt.Errorf("failed to decode bytes into dest: %w", err)
}
return nil
}

0 comments on commit 16d7b8f

Please sign in to comment.