diff --git a/README.md b/README.md index caffffb..21ccb08 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,8 @@ func main() { ### Single types +#### Integer + ```go func main () { intType := parco.Int(binary.LittleEndian) @@ -129,8 +131,65 @@ func main () { n, _ := intType.Parse(buf) log.Println(n == math.MaxInt) } + + ``` +#### Array of structs + + +```go +type ( + Animal struct { + Age uint8 + Specie string + } +) + +func main() { + animalBuilder := parco.Builder[Animal](parco.ObjectFactory[Animal]()). + SmallVarchar( + func(a *Animal) string { return a.Specie }, + func(a *Animal, specie string) { a.Specie = specie }, + ). + UInt8( + func(a *Animal) uint8 { return a.Age }, + func(a *Animal, age uint8) { a.Age = age }, + ) + + animalsType := parco.Array[Animal]( + intType, + parco.Struct[Animal](animalBuilder), + ) + + payload := []Animal{ + { + Specie: "cat", + Age: 32, + }, + { + Specie: "dog", + Age: 12, + }, + } + + _ = animalsType.Compile(parco.Slice[Animal](payload), buf) + + log.Println(buf.Bytes()) + + res, _ := animalsType.Parse(buf) + + log.Println(res.Len()) + + _ = res.Range(func(animal Animal) error { + log.Println(animal) + return nil + }) +} +``` + +--- + ### Supported fields | Field | Status | Size | diff --git a/field_struct.go b/field_struct.go index bf6adf2..8272e61 100644 --- a/field_struct.go +++ b/field_struct.go @@ -8,14 +8,9 @@ type ( CompilerType[T] } - structType[T any] struct { - ParserType[T] - CompilerType[T] - } - structField[T, U any] struct { id string - inner structType[U] + inner StructType[U] setter Setter[T, U] getter Getter[T, U] } @@ -46,10 +41,7 @@ func newStructField[T, U any]( parser ParserType[U], ) Field[T, U] { return structField[T, U]{ - inner: structType[U]{ - ParserType: parser, - CompilerType: compiler, - }, + inner: StructParco[U](parser, compiler), setter: setter, getter: getter, } diff --git a/type_struct.go b/type_struct.go new file mode 100644 index 0000000..f8b0373 --- /dev/null +++ b/type_struct.go @@ -0,0 +1,36 @@ +package parco + +type ( + StructType[T any] struct { + ParserType[T] + CompilerType[T] + } +) + +func (s StructType[T]) ByteLength() int { + panic("not implemented") +} + +func Struct[T any](b ModelBuilder[T]) StructType[T] { + parser, compiler := b.ParCo() + return StructParco[T](parser, compiler) +} + +func StructPar[T any](parser ParserType[T]) StructType[T] { + return StructType[T]{ + ParserType: parser, + } +} + +func StructCo[T any](compiler CompilerType[T]) StructType[T] { + return StructType[T]{ + CompilerType: compiler, + } +} + +func StructParco[T any](parser ParserType[T], compiler CompilerType[T]) StructType[T] { + return StructType[T]{ + ParserType: parser, + CompilerType: compiler, + } +}