diff --git a/bytesconv/serialization.go b/bytesconv/serialization.go new file mode 100644 index 0000000..8b85482 --- /dev/null +++ b/bytesconv/serialization.go @@ -0,0 +1,22 @@ +package bytesconv + +import ( + "bytes" + "encoding/gob" +) + +func Encode(v any) ([]byte, error) { + var buf = new(bytes.Buffer) + enc := gob.NewEncoder(buf) + if err := enc.Encode(v); err != nil { + return nil, err + } + + return buf.Bytes(), nil +} + +func Decode(b []byte, out any) error { + buf := bytes.NewBuffer(b) + dec := gob.NewDecoder(buf) + return dec.Decode(out) +} diff --git a/bytesconv/serialization_test.go b/bytesconv/serialization_test.go new file mode 100644 index 0000000..9567a27 --- /dev/null +++ b/bytesconv/serialization_test.go @@ -0,0 +1,27 @@ +package bytesconv + +import ( + "encoding/json" + "testing" +) + +type SimpleUser struct { + FirstName string + LastName string +} + +func TestGob(t *testing.T) { + u := SimpleUser{FirstName: "Radomir", LastName: "Sohlich"} + buf, err := Encode(u) + t.Log("Gob", BytesResult(buf).Hex(), err) + + var u2 SimpleUser + if err := Decode(buf, &u2); err != nil { + t.Fatal(err) + } + + jBytes, _ := json.Marshal(u2) + t.Log("Json:", BytesResult(jBytes).Hex()) + + t.Logf("%+v", u2) +}