Great! Let's break down the requirements and build a Go (Golang) (de)serialization system step by step.
Requirements Recap
- Schema: User specifies a schema as a string, e.g.:
"int data"
"int data, string book"
"date birthday, string name, string homeaddress, string workaddress null"
- Nested schemas (e.g.,
"int id, struct{string name, int age} person")
- Serialization: Convert a value (map or struct) to a byte slice, respecting field order.
- Deserialization: Convert a byte slice back to a value.
- Variable length fields: Use length prefixes.
- Nullable fields: Use a bitmap at the start.
- Nested schemas: Flattened.
Step 1: Schema Parsing
Let's define a simple schema parser. We'll support:
int (int32)
string
date (let's use YYYYMMDD as int32 for simplicity)
null (nullable)
struct{...} for nesting
Schema Representation
type FieldType int
const (
TypeInt FieldType = iota
TypeString
TypeDate
TypeStruct
)
type Field struct {
Name string
Type FieldType
Nullable bool
Fields []Field // For nested structs
}
Schema Parser (Simplified)
import (
"strings"
"fmt"
"regexp"
)
func ParseSchema(schema string) ([]Field, error) {
// This is a simple parser, not a full one!
fields := []Field{}
parts := strings.Split(schema, ",")
for _, part := range parts {
part = strings.TrimSpace(part)
nullable := false
if strings.HasSuffix(part, " null") {
nullable = true
part = strings.TrimSuffix(part, " null")
}
tokens := strings.Fields(part)
if len(tokens) < 2 {
return nil, fmt.Errorf("invalid field: %s", part)
}
typ, name := tokens[0], tokens[1]
switch typ {
case "int":
fields = append(fields, Field{Name: name, Type: TypeInt, Nullable: nullable})
case "string":
fields = append(fields, Field{Name: name, Type: TypeString, Nullable: nullable})
case "date":
fields = append(fields, Field{Name: name, Type: TypeDate, Nullable: nullable})
default:
// struct{...}
if strings.HasPrefix(typ, "struct{") && strings.HasSuffix(typ, "}") {
inner := typ[len("struct{") : len(typ)-1]
nestedFields, err := ParseSchema(inner)
if err != nil {
return nil, err
}
fields = append(fields, Field{Name: name, Type: TypeStruct, Nullable: nullable, Fields: nestedFields})
} else {
return nil, fmt.Errorf("unknown type: %s", typ)
}
}
}
return fields, nil
}
Step 2: Serialization
Nullable Bitmap
- For each nullable field, 1 bit in a bitmap at the start.
Serialization Function
Assume input is a map[string]interface{}.
import (
"bytes"
"encoding/binary"
"errors"
)
func serializeField(buf *bytes.Buffer, field Field, value interface{}, nullBitmap *[]byte, nullIndex *int) error {
if field.Nullable {
// Set bitmap bit
isNull := value == nil
byteIdx := *nullIndex / 8
bitIdx := *nullIndex % 8
if isNull {
(*nullBitmap)[byteIdx] |= 1 << bitIdx
}
*nullIndex++
if isNull {
return nil // Don't serialize value
}
}
switch field.Type {
case TypeInt, TypeDate:
v, ok := value.(int)
if !ok {
return errors.New("expected int")
}
return binary.Write(buf, binary.LittleEndian, int32(v))
case TypeString:
v, ok := value.(string)
if !ok {
return errors.New("expected string")
}
// Length prefix
if err := binary.Write(buf, binary.LittleEndian, int32(len(v))); err != nil {
return err
}
_, err := buf.Write([]byte(v))
return err
case TypeStruct:
m, ok := value.(map[string]interface{})
if !ok {
return errors.New("expected map for struct")
}
for _, f := range field.Fields {
if err := serializeField(buf, f, m[f.Name], nullBitmap, nullIndex); err != nil {
return err
}
}
return nil
}
return errors.New("unknown type")
}
func Serialize(schema []Field, data map[string]interface{}) ([]byte, error) {
// Count nullable fields
nullableCount := 0
var countNullable func(fields []Field)
countNullable = func(fields []Field) {
for _, f := range fields {
if f.Nullable {
nullableCount++
}
if f.Type == TypeStruct {
countNullable(f.Fields)
}
}
}
countNullable(schema)
nullBitmap := make([]byte, (nullableCount+7)/8)
nullIndex := 0
buf := &bytes.Buffer{}
// Reserve space for nullBitmap
buf.Write(nullBitmap)
for _, field := range schema {
if err := serializeField(buf, field, data[field.Name], &nullBitmap, &nullIndex); err != nil {
return nil, err
}
}
// Write actual nullBitmap at the start
out := buf.Bytes()
copy(out[:len(nullBitmap)], nullBitmap)
return out, nil
}
Step 3: Deserialization
func deserializeField(buf *bytes.Reader, field Field, nullBitmap []byte, nullIndex *int) (interface{}, error) {
if field.Nullable {
byteIdx := *nullIndex / 8
bitIdx := *nullIndex % 8
isNull := (nullBitmap[byteIdx] & (1 << bitIdx)) != 0
*nullIndex++
if isNull {
return nil, nil
}
}
switch field.Type {
case TypeInt, TypeDate:
var v int32
if err := binary.Read(buf, binary.LittleEndian, &v); err != nil {
return nil, err
}
return int(v), nil
case TypeString:
var l int32
if err := binary.Read(buf, binary.LittleEndian, &l); err != nil {
return nil, err
}
b := make([]byte, l)
if _, err := buf.Read(b); err != nil {
return nil, err
}
return string(b), nil
case TypeStruct:
m := map[string]interface{}{}
for _, f := range field.Fields {
v, err := deserializeField(buf, f, nullBitmap, nullIndex)
if err != nil {
return nil, err
}
m[f.Name] = v
}
return m, nil
}
return nil, errors.New("unknown type")
}
func Deserialize(schema []Field, data []byte) (map[string]interface{}, error) {
// Count nullable fields
nullableCount := 0
var countNullable func(fields []Field)
countNullable = func(fields []Field) {
for _, f := range fields {
if f.Nullable {
nullableCount++
}
if f.Type == TypeStruct {
countNullable(f.Fields)
}
}
}
countNullable(schema)
nullBitmap := data[:(nullableCount+7)/8]
buf := bytes.NewReader(data[(nullableCount+7)/8:])
nullIndex := 0
result := map[string]interface{}{}
for _, field := range schema {
v, err := deserializeField(buf, field, nullBitmap, &nullIndex)
if err != nil {
return nil, err
}
result[field.Name] = v
}
return result, nil
}
Step 4: Example Usage
func main() {
schemaStr := "int id, string name null, struct{int age, string city null} person"
schema, err := ParseSchema(schemaStr)
if err != nil {
panic(err)
}
data := map[string]interface{}{
"id": 42,
"name": nil,
"person": map[string]interface{}{
"age": 30,
"city": "Berlin",
},
}
serialized, err := Serialize(schema, data)
if err != nil {
panic(err)
}
fmt.Printf("Serialized: %x\n", serialized)
deserialized, err := Deserialize(schema, serialized)
if err != nil {
panic(err)
}
fmt.Printf("Deserialized: %+v\n", deserialized)
}
Next Steps
- This is a basic implementation. For production, you'd want a more robust parser, error handling, and support for more types.
- You can extend the parser to support arrays, floats, etc.
- For nested structs, flattening is handled by recursing into fields.
Let me know if you want to see a full working example, or if you want to add more types or features!