Best Syzkaller code snippet using serializer.byte
serializable_test.go
Source:serializable_test.go
...9 "github.com/stretchr/testify/assert"10 "github.com/iotaledger/hive.go/serializer/v2"11)12const (13 TypeA byte = 014 TypeB byte = 115 aKeyLength = 1616 bNameLength = 3217 typeALength = serializer.SmallTypeDenotationByteSize + aKeyLength18 typeBLength = serializer.SmallTypeDenotationByteSize + bNameLength19)20var (21 ErrUnknownDummyType = errors.New("unknown example type")22 dummyTypeArrayRules = &serializer.ArrayRules{23 Guards: serializer.SerializableGuard{24 ReadGuard: DummyTypeSelector,25 WriteGuard: func(seri serializer.Serializable) error {26 switch seri.(type) {27 case *A:28 case *B:29 return ErrUnknownDummyType30 }31 return nil32 },33 },34 }35)36func DummyTypeSelector(dummyType uint32) (serializer.Serializable, error) {37 var seri serializer.Serializable38 switch byte(dummyType) {39 case TypeA:40 seri = &A{}41 case TypeB:42 seri = &B{}43 default:44 return nil, ErrUnknownDummyType45 }46 return seri, nil47}48type Keyer interface {49 GetKey() [aKeyLength]byte50}51type A struct {52 Key [aKeyLength]byte53}54func (a *A) String() string {55 return "A"56}57func (a *A) GetKey() [16]byte {58 return a.Key59}60func (a *A) MarshalJSON() ([]byte, error) {61 panic("implement me")62}63func (a *A) UnmarshalJSON(i []byte) error {64 panic("implement me")65}66func (a *A) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {67 data = data[serializer.SmallTypeDenotationByteSize:]68 copy(a.Key[:], data[:aKeyLength])69 return typeALength, nil70}71func (a *A) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {72 var b [typeALength]byte73 b[0] = TypeA74 copy(b[serializer.SmallTypeDenotationByteSize:], a.Key[:])75 return b[:], nil76}77type As []*A78func (a As) ToSerializables() serializer.Serializables {79 seris := make(serializer.Serializables, len(a))80 for i, x := range a {81 seris[i] = x82 }83 return seris84}85func (a *As) FromSerializables(seris serializer.Serializables) {86 *a = make(As, len(seris))87 for i, seri := range seris {88 (*a)[i] = seri.(*A)89 }90}91type Keyers []Keyer92func (k Keyers) ToSerializables() serializer.Serializables {93 seris := make(serializer.Serializables, len(k))94 for i, x := range k {95 seris[i] = x.(serializer.Serializable)96 }97 return seris98}99func (k *Keyers) FromSerializables(seris serializer.Serializables) {100 *k = make(Keyers, len(seris))101 for i, seri := range seris {102 (*k)[i] = seri.(Keyer)103 }104}105// RandBytes returns length amount random bytes.106func RandBytes(length int) []byte {107 var b []byte108 for i := 0; i < length; i++ {109 b = append(b, byte(rand.Intn(256)))110 }111 return b112}113func randSerializedA() []byte {114 var b [typeALength]byte115 b[0] = TypeA116 keyData := RandBytes(aKeyLength)117 copy(b[serializer.SmallTypeDenotationByteSize:], keyData)118 return b[:]119}120func randA() *A {121 var k [aKeyLength]byte122 copy(k[:], RandBytes(aKeyLength))123 return &A{Key: k}124}125type B struct {126 Name [bNameLength]byte127}128func (b *B) String() string {129 return "B"130}131func (b *B) MarshalJSON() ([]byte, error) {132 panic("implement me")133}134func (b *B) UnmarshalJSON(i []byte) error {135 panic("implement me")136}137func (b *B) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {138 data = data[serializer.SmallTypeDenotationByteSize:]139 copy(b.Name[:], data[:bNameLength])140 return typeBLength, nil141}142func (b *B) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {143 var bf [typeBLength]byte144 bf[0] = TypeB145 copy(bf[serializer.SmallTypeDenotationByteSize:], b.Name[:])146 return bf[:], nil147}148func randB() *B {149 var n [bNameLength]byte150 copy(n[:], RandBytes(bNameLength))151 return &B{Name: n}152}153func TestDeserializeA(t *testing.T) {154 seriA := randSerializedA()155 objA := &A{}156 bytesRead, err := objA.Deserialize(seriA, serializer.DeSeriModePerformValidation, nil)157 assert.NoError(t, err)158 assert.Equal(t, len(seriA), bytesRead)159 assert.Equal(t, seriA[serializer.SmallTypeDenotationByteSize:], objA.Key[:])160}161func TestLexicalOrderedByteSlices(t *testing.T) {162 type test struct {163 name string164 source serializer.LexicalOrderedByteSlices165 target serializer.LexicalOrderedByteSlices166 }167 tests := []test{168 {169 name: "ok - order by first ele",170 source: serializer.LexicalOrderedByteSlices{171 {3, 2, 1},172 {2, 3, 1},173 {1, 2, 3},174 },175 target: serializer.LexicalOrderedByteSlices{176 {1, 2, 3},177 {2, 3, 1},178 {3, 2, 1},179 },180 },181 {182 name: "ok - order by last ele",183 source: serializer.LexicalOrderedByteSlices{184 {1, 1, 3},185 {1, 1, 2},186 {1, 1, 1},187 },188 target: serializer.LexicalOrderedByteSlices{189 {1, 1, 1},190 {1, 1, 2},191 {1, 1, 3},192 },193 },194 }195 for _, tt := range tests {196 t.Run(tt.name, func(t *testing.T) {197 sort.Sort(tt.source)198 assert.Equal(t, tt.target, tt.source)199 })200 }201}202func TestRemoveDupsAndSortByLexicalOrderArrayOf32Bytes(t *testing.T) {203 type test struct {204 name string205 source serializer.LexicalOrdered32ByteArrays206 target serializer.LexicalOrdered32ByteArrays207 }208 tests := []test{209 {210 name: "ok - dups removed and order by first ele",211 source: serializer.LexicalOrdered32ByteArrays{212 {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},213 {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},214 {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},215 {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},216 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},217 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},218 },219 target: serializer.LexicalOrdered32ByteArrays{220 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},221 {2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},222 {3, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},223 },224 },225 {226 name: "ok - dups removed and order by last ele",227 source: serializer.LexicalOrdered32ByteArrays{228 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34},229 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34},230 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33},231 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},232 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},233 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},234 },235 target: serializer.LexicalOrdered32ByteArrays{236 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},237 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33},238 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34},239 },240 },241 }242 for _, tt := range tests {243 t.Run(tt.name, func(t *testing.T) {244 tt.source = serializer.RemoveDupsAndSortByLexicalOrderArrayOf32Bytes(tt.source)245 assert.Equal(t, tt.target, tt.source)246 })247 }248}249func TestSerializationMode_HasMode(t *testing.T) {250 type args struct {251 mode serializer.DeSerializationMode252 }253 tests := []struct {254 name string255 sm serializer.DeSerializationMode256 args args257 want bool258 }{259 {260 "has no validation",261 serializer.DeSeriModeNoValidation,262 args{mode: serializer.DeSeriModePerformValidation},263 false,264 },265 {266 "has validation",267 serializer.DeSeriModePerformValidation,268 args{mode: serializer.DeSeriModePerformValidation},269 true,270 },271 }272 for _, tt := range tests {273 t.Run(tt.name, func(t *testing.T) {274 if got := tt.sm.HasMode(tt.args.mode); got != tt.want {275 t.Errorf("HasMode() = %v, want %v", got, tt.want)276 }277 })278 }279}280func TestArrayValidationMode_HasMode(t *testing.T) {281 type args struct {282 mode serializer.ArrayValidationMode283 }284 tests := []struct {285 name string286 sm serializer.ArrayValidationMode287 args args288 want bool289 }{290 {291 "has no validation",292 serializer.ArrayValidationModeNone,293 args{mode: serializer.ArrayValidationModeNoDuplicates},294 false,295 },296 {297 "has mode duplicates",298 serializer.ArrayValidationModeNoDuplicates,299 args{mode: serializer.ArrayValidationModeNoDuplicates},300 true,301 },302 {303 "has mode lexical order",304 serializer.ArrayValidationModeLexicalOrdering,305 args{mode: serializer.ArrayValidationModeLexicalOrdering},306 true,307 },308 }309 for _, tt := range tests {310 t.Run(tt.name, func(t *testing.T) {311 if got := tt.sm.HasMode(tt.args.mode); got != tt.want {312 t.Errorf("HasMode() = %v, want %v", got, tt.want)313 }314 })315 }316}317func TestArrayRules_ElementUniqueValidator(t *testing.T) {318 type test struct {319 name string320 args [][]byte321 valid bool322 ar *serializer.ArrayRules323 }324 tests := []test{325 {326 name: "ok - no dups",327 args: [][]byte{328 {1, 2, 3},329 {2, 3, 1},330 {3, 2, 1},331 },332 ar: &serializer.ArrayRules{},333 valid: true,334 },335 {336 name: "not ok - dups",337 args: [][]byte{338 {1, 1, 1},339 {1, 1, 2},340 {1, 1, 3},341 {1, 1, 3},342 },343 ar: &serializer.ArrayRules{},344 valid: false,345 },346 {347 name: "not ok - dups with reduction",348 args: [][]byte{349 {1, 1, 1},350 {1, 1, 2},351 {1, 1, 3},352 },353 ar: &serializer.ArrayRules{354 UniquenessSliceFunc: func(next []byte) []byte {355 return next[:2]356 },357 },358 valid: false,359 },360 }361 for _, tt := range tests {362 t.Run(tt.name, func(t *testing.T) {363 arrayElementValidator := tt.ar.ElementUniqueValidator()364 valid := true365 for i := range tt.args {366 element := tt.args[i]367 if err := arrayElementValidator(i, element); err != nil {368 valid = false369 }370 }371 assert.Equal(t, tt.valid, valid)372 })373 }374}375func TestArrayRules_Bounds(t *testing.T) {376 type test struct {377 name string378 args [][]byte379 min int380 max int381 valid bool382 }383 arrayRules := serializer.ArrayRules{}384 tests := []test{385 {386 name: "ok - min",387 args: [][]byte{388 {1},389 },390 min: 1,391 max: 3,392 valid: true,393 },394 {395 name: "ok - max",396 args: [][]byte{397 {1},398 {2},399 {3},400 },401 min: 1,402 max: 3,403 valid: true,404 },405 {406 name: "not ok - min",407 args: [][]byte{408 {1},409 {2},410 {3},411 },412 min: 4,413 max: 5,414 valid: false,415 },416 {417 name: "not ok - max",418 args: [][]byte{419 {1},420 {2},421 {3},422 },423 min: 1,424 max: 2,425 valid: false,426 },427 }428 for _, tt := range tests {429 t.Run(tt.name, func(t *testing.T) {430 arrayRules.Min = uint(tt.min)431 arrayRules.Max = uint(tt.max)432 err := arrayRules.CheckBounds(uint(len(tt.args)))433 assert.Equal(t, tt.valid, err == nil)434 })435 }436}437func TestArrayRules_LexicalOrderValidator(t *testing.T) {438 type test struct {439 name string440 args [][]byte441 valid bool442 ar *serializer.ArrayRules443 }444 tests := []test{445 {446 name: "ok - order by first ele",447 args: [][]byte{448 {1, 2, 3},449 {2, 3, 1},450 {3, 2, 1},451 },452 ar: &serializer.ArrayRules{},453 valid: true,454 },455 {456 name: "ok - order by last ele",457 args: [][]byte{458 {1, 1, 1},459 {1, 1, 2},460 {1, 1, 3},461 },462 ar: &serializer.ArrayRules{},463 valid: true,464 },465 {466 name: "not ok",467 args: [][]byte{468 {2, 1, 1},469 {1, 1, 2},470 {3, 1, 3},471 },472 ar: &serializer.ArrayRules{},473 valid: false,474 },475 }476 for _, tt := range tests {477 t.Run(tt.name, func(t *testing.T) {478 arrayElementValidator := tt.ar.LexicalOrderValidator()479 valid := true480 for i := range tt.args {481 element := tt.args[i]482 if err := arrayElementValidator(i, element); err != nil {483 valid = false484 }485 }486 assert.Equal(t, tt.valid, valid)487 })488 }489}490func TestArrayRules_LexicalOrderWithoutDupsValidator(t *testing.T) {491 type test struct {492 name string493 args [][]byte494 valid bool495 ar *serializer.ArrayRules496 }497 tests := []test{498 {499 name: "ok - order by first ele - no dups",500 args: [][]byte{501 {1, 2, 3},502 {2, 3, 1},503 {3, 2, 1},504 },505 ar: &serializer.ArrayRules{},506 valid: true,507 },508 {509 name: "ok - order by last ele - no dups",510 args: [][]byte{511 {1, 1, 1},512 {1, 1, 2},513 {1, 1, 3},514 },515 ar: &serializer.ArrayRules{},516 valid: true,517 },518 {519 name: "not ok - dups",520 args: [][]byte{521 {1, 1, 1},522 {1, 1, 2},523 {1, 1, 3},524 {1, 1, 3},525 },526 ar: &serializer.ArrayRules{},527 valid: false,528 },529 {530 name: "not ok - order",531 args: [][]byte{532 {2, 1, 1},533 {1, 1, 2},534 {3, 1, 3},535 },536 ar: &serializer.ArrayRules{},537 valid: false,538 },539 {540 name: "not ok - dups with reduction",541 args: [][]byte{542 {1, 1, 1},543 {1, 1, 2},544 {1, 1, 3},545 },546 ar: &serializer.ArrayRules{547 UniquenessSliceFunc: func(next []byte) []byte {548 return next[:2]549 },550 },551 valid: false,552 },553 }554 for _, tt := range tests {555 t.Run(tt.name, func(t *testing.T) {556 arrayElementValidator := tt.ar.LexicalOrderWithoutDupsValidator()557 valid := true558 for i := range tt.args {559 element := tt.args[i]560 if err := arrayElementValidator(i, element); err != nil {561 valid = false562 }563 }564 assert.Equal(t, tt.valid, valid)565 })566 }567}568func TestArrayRules_AtMostOneOfEachTypeValidatorValidator(t *testing.T) {569 type test struct {570 name string571 args [][]byte572 valid bool573 ar *serializer.ArrayRules574 ty serializer.TypeDenotationType575 }576 tests := []test{577 {578 name: "ok - types unique - byte",579 args: [][]byte{580 {1, 1, 1},581 {2, 2, 2},582 {3, 3, 3},583 },584 valid: true,585 ar: &serializer.ArrayRules{},586 ty: serializer.TypeDenotationByte,587 },588 {589 name: "ok - types unique - uint32",590 args: [][]byte{591 {1, 1, 1, 1},592 {2, 2, 2, 2},593 {3, 3, 3, 3},594 },595 valid: true,596 ar: &serializer.ArrayRules{},597 ty: serializer.TypeDenotationUint32,598 },599 {600 name: "not ok - types not unique - byte",601 args: [][]byte{602 {1, 1, 1},603 {1, 2, 2},604 {3, 3, 3},605 },606 valid: false,607 ar: &serializer.ArrayRules{},608 ty: serializer.TypeDenotationByte,609 },610 {611 name: "not ok - types not unique - uint32",612 args: [][]byte{613 {1, 1, 1, 1},614 {2, 2, 2, 2},615 {1, 1, 1, 1},616 },617 valid: false,618 ar: &serializer.ArrayRules{},619 ty: serializer.TypeDenotationUint32,620 },621 }622 for _, tt := range tests {623 t.Run(tt.name, func(t *testing.T) {624 arrayElementValidator := tt.ar.AtMostOneOfEachTypeValidator(tt.ty)625 valid := true626 for i := range tt.args {...
serix_test.go
Source:serix_test.go
...22 defaultErrProducer = func(err error) error { return err }23 defaultWriteGuard = func(seri serializer.Serializable) error { return nil }24)25type Bool bool26func (b Bool) MarshalJSON() ([]byte, error) {27 // ToDo: implement me28 panic("implement me")29}30func (b Bool) UnmarshalJSON(bytes []byte) error {31 // ToDo: implement me32 panic("implement me")33}34func (b Bool) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {35 // ToDo: implement me36 panic("implement me")37}38func (b Bool) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {39 ser := serializer.NewSerializer()40 ser.WriteBool(bool(b), defaultErrProducer)41 return ser.Serialize()42}43type Bools []Bool44var boolsLenType = serix.LengthPrefixTypeAsUint1645func (bs Bools) MarshalJSON() ([]byte, error) {46 // ToDo: implement me47 panic("implement me")48}49func (bs Bools) UnmarshalJSON(bytes []byte) error {50 // ToDo: implement me51 panic("implement me")52}53func (bs Bools) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {54 // ToDo: implement me55 panic("implement me")56}57func (bs Bools) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {58 s := serializer.NewSerializer()59 s.WriteSliceOfObjects(bs, deSeriMode, deSeriCtx, serializer.SeriLengthPrefixType(boolsLenType), defaultArrayRules, defaultErrProducer)60 return s.Serialize()61}62func (bs Bools) ToSerializables() serializer.Serializables {63 serializables := make(serializer.Serializables, len(bs))64 for i, b := range bs {65 serializables[i] = b66 }67 return serializables68}69func (bs Bools) FromSerializables(seris serializer.Serializables) {70 // ToDo: implement me71 panic("implement me")72}73type SimpleStruct struct {74 Bool bool `serix:"0"`75 Uint uint64 `serix:"1"`76 String string `serix:"2,lengthPrefixType=uint16"`77 Bytes []byte `serix:"3,lengthPrefixType=uint32"`78 BytesArray [16]byte `serix:"4"`79 BigInt *big.Int `serix:"5"`80 Time time.Time `serix:"6"`81 Int uint64 `serix:"7"`82 Float float64 `serix:"8"`83}84func NewSimpleStruct() SimpleStruct {85 return SimpleStruct{86 Bool: true,87 Uint: 10,88 String: "foo",89 Bytes: []byte{1, 2, 3},90 BytesArray: [16]byte{3, 2, 1},91 BigInt: big.NewInt(8),92 Time: time.Unix(1000, 1000),93 Int: 23,94 Float: 4.44,95 }96}97var simpleStructObjectCode = uint32(0)98func (ss SimpleStruct) MarshalJSON() ([]byte, error) {99 // ToDo: implement me100 panic("implement me")101}102func (ss SimpleStruct) UnmarshalJSON(bytes []byte) error {103 // ToDo: implement me104 panic("implement me")105}106func (ss SimpleStruct) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {107 // ToDo: implement me108 panic("implement me")109}110func (ss SimpleStruct) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {111 s := serializer.NewSerializer()112 s.WriteNum(simpleStructObjectCode, defaultErrProducer)113 s.WriteBool(ss.Bool, defaultErrProducer)114 s.WriteNum(ss.Uint, defaultErrProducer)115 s.WriteString(ss.String, serializer.SeriLengthPrefixTypeAsUint16, defaultErrProducer, 0, 0)116 s.WriteVariableByteSlice(ss.Bytes, serializer.SeriLengthPrefixTypeAsUint32, defaultErrProducer, 0, 0)117 s.WriteBytes(ss.BytesArray[:], defaultErrProducer)118 s.WriteUint256(ss.BigInt, defaultErrProducer)119 s.WriteTime(ss.Time, defaultErrProducer)120 s.WriteNum(ss.Int, defaultErrProducer)121 s.WriteNum(ss.Float, defaultErrProducer)122 return s.Serialize()123}124type Interface interface {125 Method()126 serix.Serializable127 serix.Deserializable128}129type InterfaceImpl struct {130 interfaceImpl `serix:"0"`131}132type interfaceImpl struct {133 A uint8 `serix:"0"`134 B uint8 `serix:"1"`135}136func (ii *InterfaceImpl) Encode() ([]byte, error) {137 return testAPI.Encode(context.Background(), ii.interfaceImpl, serix.WithValidation())138}139func (ii *InterfaceImpl) Decode(b []byte) (consumedBytes int, err error) {140 return testAPI.Decode(context.Background(), b, &ii.interfaceImpl, serix.WithValidation())141}142var interfaceImplObjectCode = uint32(1)143func (ii *InterfaceImpl) Method() {}144func (ii *InterfaceImpl) MarshalJSON() ([]byte, error) {145 // ToDo: implement me146 panic("implement me")147}148func (ii *InterfaceImpl) UnmarshalJSON(bytes []byte) error {149 // ToDo: implement me150 panic("implement me")151}152func (ii *InterfaceImpl) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {153 // ToDo: implement me154 panic("implement me")155}156func (ii *InterfaceImpl) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {157 ser := serializer.NewSerializer()158 ser.WriteNum(interfaceImplObjectCode, defaultErrProducer)159 ser.WriteNum(ii.A, defaultErrProducer)160 ser.WriteNum(ii.B, defaultErrProducer)161 return ser.Serialize()162}163type StructWithInterface struct {164 Interface Interface `serix:"0"`165}166func (si StructWithInterface) MarshalJSON() ([]byte, error) {167 // ToDo: implement me168 panic("implement me")169}170func (si StructWithInterface) UnmarshalJSON(bytes []byte) error {171 // ToDo: implement me172 panic("implement me")173}174func (si StructWithInterface) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {175 // ToDo: implement me176 panic("implement me")177}178func (si StructWithInterface) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {179 s := serializer.NewSerializer()180 s.WriteObject(si.Interface.(serializer.Serializable), defaultSeriMode, deSeriCtx, defaultWriteGuard, defaultErrProducer)181 return s.Serialize()182}183type StructWithOptionalField struct {184 Optional *ExportedStruct `serix:"0,optional"`185}186func (so StructWithOptionalField) MarshalJSON() ([]byte, error) {187 // ToDo: implement me188 panic("implement me")189}190func (so StructWithOptionalField) UnmarshalJSON(bytes []byte) error {191 // ToDo: implement me192 panic("implement me")193}194func (so StructWithOptionalField) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {195 // ToDo: implement me196 panic("implement me")197}198func (so StructWithOptionalField) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {199 s := serializer.NewSerializer()200 s.WritePayloadLength(0, defaultErrProducer)201 return s.Serialize()202}203type StructWithEmbeddedStructs struct {204 unexportedStruct `serix:"0"`205 ExportedStruct `serix:"1,nest"`206}207func (se StructWithEmbeddedStructs) MarshalJSON() ([]byte, error) {208 // ToDo: implement me209 panic("implement me")210}211func (se StructWithEmbeddedStructs) UnmarshalJSON(bytes []byte) error {212 // ToDo: implement me213 panic("implement me")214}215func (se StructWithEmbeddedStructs) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {216 // ToDo: implement me217 panic("implement me")218}219func (se StructWithEmbeddedStructs) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {220 s := serializer.NewSerializer()221 s.WriteNum(se.unexportedStruct.Foo, defaultErrProducer)222 s.WriteNum(exportedStructObjectCode, defaultErrProducer)223 s.WriteNum(se.ExportedStruct.Bar, defaultErrProducer)224 return s.Serialize()225}226type unexportedStruct struct {227 Foo uint64 `serix:"0"`228}229type ExportedStruct struct {230 Bar uint64 `serix:"0"`231}232var exportedStructObjectCode = uint32(3)233type Map map[uint64]uint64234var mapLenType = serix.LengthPrefixTypeAsUint32235func (m Map) MarshalJSON() ([]byte, error) {236 // ToDo: implement me237 panic("implement me")238}239func (m Map) UnmarshalJSON(bytes []byte) error {240 // ToDo: implement me241 panic("implement me")242}243func (m Map) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {244 // ToDo: implement me245 panic("implement me")246}247func (m Map) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {248 bytes := make([][]byte, len(m))249 var i int250 for k, v := range m {251 s := serializer.NewSerializer()252 s.WriteNum(k, defaultErrProducer)253 s.WriteNum(v, defaultErrProducer)254 b, err := s.Serialize()255 if err != nil {256 return nil, err257 }258 bytes[i] = b259 i++260 }261 s := serializer.NewSerializer()262 mode := defaultSeriMode | serializer.DeSeriModePerformLexicalOrdering263 arrayRules := &serializer.ArrayRules{ValidationMode: serializer.ArrayValidationModeLexicalOrdering}264 s.WriteSliceOfByteSlices(bytes, mode, serializer.SeriLengthPrefixType(mapLenType), arrayRules, defaultErrProducer)265 return s.Serialize()266}267type CustomSerializable int268func (cs CustomSerializable) MarshalJSON() ([]byte, error) {269 // ToDo: implement me270 panic("implement me")271}272func (cs CustomSerializable) UnmarshalJSON(bytes []byte) error {273 // ToDo: implement me274 panic("implement me")275}276func (cs CustomSerializable) Deserialize(data []byte, deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) (int, error) {277 // ToDo: implement me278 panic("implement me")279}280func (cs CustomSerializable) Serialize(deSeriMode serializer.DeSerializationMode, deSeriCtx interface{}) ([]byte, error) {281 return cs.Encode()282}283func (cs CustomSerializable) Encode() ([]byte, error) {284 b := []byte(fmt.Sprintf("int: %d", cs))285 return b, nil286}287func (cs *CustomSerializable) Decode(b []byte) (int, error) {288 _, err := fmt.Sscanf(string(b), "int: %d", cs)289 if err != nil {290 return 0, err291 }292 return len(b), nil293}294type ObjectForSyntacticValidation struct{}295var errSyntacticValidation = errors.New("syntactic validation failed")296func SyntacticValidation(ctx context.Context, obj ObjectForSyntacticValidation) error {297 return errSyntacticValidation298}299type ObjectForBytesValidation struct{}300var errBytesValidation = errors.New("bytes validation failed")301func BytesValidation(ctx context.Context, b []byte) error {302 return errBytesValidation303}304func TestMain(m *testing.M) {305 exitCode := func() int {306 if err := testAPI.RegisterTypeSettings(307 SimpleStruct{},308 serix.TypeSettings{}.WithObjectType(simpleStructObjectCode),309 ); err != nil {310 log.Panic(err)311 }312 if err := testAPI.RegisterTypeSettings(313 InterfaceImpl{},314 serix.TypeSettings{}.WithObjectType(interfaceImplObjectCode),315 ); err != nil {316 log.Panic(err)317 }318 if err := testAPI.RegisterTypeSettings(319 ExportedStruct{},320 serix.TypeSettings{}.WithObjectType(exportedStructObjectCode),321 ); err != nil {322 log.Panic(err)323 }324 if err := testAPI.RegisterInterfaceObjects((*Interface)(nil), (*InterfaceImpl)(nil)); err != nil {325 log.Panic(err)326 }327 if err := testAPI.RegisterValidators(ObjectForSyntacticValidation{}, nil, SyntacticValidation); err != nil {328 log.Panic(err)329 }330 if err := testAPI.RegisterValidators(ObjectForBytesValidation{}, BytesValidation, nil); err != nil {331 log.Panic(err)332 }333 return m.Run()334 }()335 os.Exit(exitCode)336}337func TestMinMax(t *testing.T) {338 type paras struct {339 api *serix.API340 encodeInput any341 decodeInput []byte342 }343 type test struct {344 name string345 paras paras346 error bool347 }348 tests := []test{349 {350 name: "ok - string in bounds",351 paras: func() paras {352 type example struct {353 Str string `serix:"0,minLen=5,maxLen=10,lengthPrefixType=uint8"`354 }355 api := serix.NewAPI()356 must(api.RegisterTypeSettings(example{}, serix.TypeSettings{}.WithObjectType(uint8(0))))357 return paras{358 api: api,359 encodeInput: &example{Str: "abcde"},360 decodeInput: []byte{0, 5, 97, 98, 99, 100, 101},361 }362 }(),363 error: false,364 },365 {366 name: "err - string out of bounds",367 paras: func() paras {368 type example struct {369 Str string `serix:"0,minLen=5,maxLen=10,lengthPrefixType=uint8"`370 }371 api := serix.NewAPI()372 must(api.RegisterTypeSettings(example{}, serix.TypeSettings{}.WithObjectType(uint8(0))))373 return paras{374 api: api,375 encodeInput: &example{Str: "abc"},376 decodeInput: []byte{0, 3, 97, 98, 99},377 }378 }(),379 error: true,380 },381 {382 name: "ok - slice in bounds",383 paras: func() paras {384 type example struct {385 Slice []byte `serix:"0,minLen=0,maxLen=10,lengthPrefixType=uint8"`386 }387 api := serix.NewAPI()388 must(api.RegisterTypeSettings(example{}, serix.TypeSettings{}.WithObjectType(uint8(0))))389 return paras{390 api: api,391 encodeInput: &example{Slice: []byte{1, 2, 3, 4, 5}},392 decodeInput: []byte{0, 5, 1, 2, 3, 4, 5},393 }394 }(),395 error: false,396 },397 {398 name: "err - slice out of bounds",399 paras: func() paras {400 type example struct {401 Slice []byte `serix:"0,minLen=0,maxLen=3,lengthPrefixType=uint8"`402 }403 api := serix.NewAPI()404 must(api.RegisterTypeSettings(example{}, serix.TypeSettings{}.WithObjectType(uint8(0))))405 return paras{406 api: api,407 encodeInput: &example{Slice: []byte{1, 2, 3, 4}},408 decodeInput: []byte{0, 4, 1, 2, 3, 4},409 }410 }(),411 error: true,412 },413 }414 for _, test := range tests {415 t.Run(test.name, func(t *testing.T) {416 t.Run("encode", func(t *testing.T) {417 _, err := test.paras.api.Encode(context.Background(), test.paras.encodeInput, serix.WithValidation())418 if test.error {419 require.Error(t, err)420 return421 }422 require.NoError(t, err)...
primitives.go
Source:primitives.go
1package serializer2import (3 "bytes"4 "encoding/binary"5 "errors"6 "strconv"7 "github.com/unixpickle/essentials"8)9func init() {10 RegisterTypedDeserializer(Bytes(nil).SerializerType(), DeserializeBytes)11 RegisterTypedDeserializer(String("").SerializerType(), DeserializeString)12 RegisterTypedDeserializer(Int(0).SerializerType(), DeserializeInt)13 RegisterTypedDeserializer(IntSlice(nil).SerializerType(), DeserializeIntSlice)14 RegisterTypedDeserializer(Int64(0).SerializerType(), DeserializeInt64)15 RegisterTypedDeserializer(Int32(0).SerializerType(), DeserializeInt32)16 RegisterTypedDeserializer(Int64Slice(nil).SerializerType(), DeserializeInt64Slice)17 RegisterTypedDeserializer(Int32Slice(nil).SerializerType(), DeserializeInt32Slice)18 RegisterTypedDeserializer(Float64(0).SerializerType(), DeserializeFloat64)19 RegisterTypedDeserializer(Float32(0).SerializerType(), DeserializeFloat32)20 RegisterTypedDeserializer(Float64Slice(nil).SerializerType(), DeserializeFloat64Slice)21 RegisterTypedDeserializer(Float32Slice(nil).SerializerType(), DeserializeFloat32Slice)22 RegisterTypedDeserializer(Bool(false).SerializerType(), DeserializeBool)23}24// Bytes is a Serializer wrapper for []byte.25type Bytes []byte26// DeserializeBytes deserializes a Bytes.27func DeserializeBytes(d []byte) (Bytes, error) {28 return d, nil29}30// Serialize serializes the object.31func (b Bytes) Serialize() ([]byte, error) {32 return b, nil33}34// SerializerType returns the unique ID used to serialize35// Bytes.36func (b Bytes) SerializerType() string {37 return "[]byte"38}39// String is a Serializer wrapper for string.40type String string41// DeserializeString deserializes a String.42func DeserializeString(d []byte) (String, error) {43 return String(d), nil44}45// Serialize serializes the object.46func (s String) Serialize() ([]byte, error) {47 return []byte(s), nil48}49// SerializerType returns the unique ID used to serialize50// a String.51func (s String) SerializerType() string {52 return "string"53}54// Int is a Serializer wrapper for an int.55type Int int56// DeserializeInt deserialize an Int.57func DeserializeInt(d []byte) (Int, error) {58 num, err := strconv.Atoi(string(d))59 if err != nil {60 return 0, essentials.AddCtx("deserialize int", err)61 }62 return Int(num), nil63}64// Serialize serializes the object.65func (i Int) Serialize() ([]byte, error) {66 return []byte(strconv.Itoa(int(i))), nil67}68// SerializerType returns the unique ID used to serialize69// an Int.70func (i Int) SerializerType() string {71 return "int"72}73// IntSlice is a Serializer wrapper for an []int.74type IntSlice []int75// DeserializeIntSlice deserializes an IntSlice.76func DeserializeIntSlice(d []byte) (slice IntSlice, err error) {77 defer essentials.AddCtxTo("deserialize IntSlice", &err)78 reader := bytes.NewBuffer(d)79 var size uint6480 if err := binary.Read(reader, binary.LittleEndian, &size); err != nil {81 return nil, err82 }83 vec := make([]int64, int(size))84 if err := binary.Read(reader, binary.LittleEndian, vec); err != nil {85 return nil, err86 }87 res := make([]int, len(vec))88 for i, x := range vec {89 res[i] = int(x)90 }91 return res, nil92}93// Serialize serializes the object.94func (i IntSlice) Serialize() ([]byte, error) {95 ints64 := make([]int64, len(i))96 for j, x := range i {97 ints64[j] = int64(x)98 }99 var w bytes.Buffer100 binary.Write(&w, binary.LittleEndian, uint64(len(i)))101 binary.Write(&w, binary.LittleEndian, ints64)102 return w.Bytes(), nil103}104// SerializerType returns the unique ID used to serialize105// an IntSlice.106func (i IntSlice) SerializerType() string {107 return "[]int"108}109// Int64 is a Serializer for a int64.110type Int64 int64111// DeserializeInt64 deserializes a Int64.112func DeserializeInt64(d []byte) (Int64, error) {113 buf := bytes.NewBuffer(d)114 var value int64115 if err := binary.Read(buf, binary.LittleEndian, &value); err != nil {116 return 0, essentials.AddCtx("deserialize int64", err)117 }118 return Int64(value), nil119}120// Serialize serializes the object.121func (i Int64) Serialize() ([]byte, error) {122 var buf bytes.Buffer123 binary.Write(&buf, binary.LittleEndian, int64(i))124 return buf.Bytes(), nil125}126// SerializerType returns the unique ID used to serialize127// a Int64.128func (i Int64) SerializerType() string {129 return "int64"130}131// Int32 is a Serializer for a int32.132type Int32 int32133// DeserializeInt32 deserializes a Int32.134func DeserializeInt32(d []byte) (Int32, error) {135 buf := bytes.NewBuffer(d)136 var value int32137 if err := binary.Read(buf, binary.LittleEndian, &value); err != nil {138 return 0, essentials.AddCtx("deserialize int32", err)139 }140 return Int32(value), nil141}142// Serialize serializes the object.143func (i Int32) Serialize() ([]byte, error) {144 var buf bytes.Buffer145 binary.Write(&buf, binary.LittleEndian, int32(i))146 return buf.Bytes(), nil147}148// SerializerType returns the unique ID used to serialize149// a Int64.150func (i Int32) SerializerType() string {151 return "int32"152}153// A Int64Slice is a Serializer for a []int64.154type Int64Slice []int64155// DeserializeInt64Slice deserializes a Int64Slice.156func DeserializeInt64Slice(d []byte) (Int64Slice, error) {157 reader := bytes.NewBuffer(d)158 var size uint64159 if err := binary.Read(reader, binary.LittleEndian, &size); err != nil {160 return nil, essentials.AddCtx("deserialize []int64", err)161 }162 vec := make([]int64, int(size))163 if err := binary.Read(reader, binary.LittleEndian, vec); err != nil {164 return nil, essentials.AddCtx("deserialize []int64", err)165 }166 return vec, nil167}168// Serialize serializes the object.169func (i Int64Slice) Serialize() ([]byte, error) {170 var w bytes.Buffer171 binary.Write(&w, binary.LittleEndian, uint64(len(i)))172 binary.Write(&w, binary.LittleEndian, []int64(i))173 return w.Bytes(), nil174}175// SerializerType returns the unique ID used to serialize176// a Int64Slice.177func (i Int64Slice) SerializerType() string {178 return "[]int64"179}180// A Int32Slice is a Serializer for a []int32.181type Int32Slice []int32182// DeserializeInt32Slice deserializes a Int32Slice.183func DeserializeInt32Slice(d []byte) (Int32Slice, error) {184 reader := bytes.NewBuffer(d)185 var size uint64186 if err := binary.Read(reader, binary.LittleEndian, &size); err != nil {187 return nil, essentials.AddCtx("deserialize []int32", err)188 }189 vec := make([]int32, int(size))190 if err := binary.Read(reader, binary.LittleEndian, vec); err != nil {191 return nil, essentials.AddCtx("deserialize []int32", err)192 }193 return vec, nil194}195// Serialize serializes the object.196func (i Int32Slice) Serialize() ([]byte, error) {197 var w bytes.Buffer198 binary.Write(&w, binary.LittleEndian, uint64(len(i)))199 binary.Write(&w, binary.LittleEndian, []int32(i))200 return w.Bytes(), nil201}202// SerializerType returns the unique ID used to serialize203// a Int32Slice.204func (i Int32Slice) SerializerType() string {205 return "[]int32"206}207// Float64 is a Serializer for a float64.208type Float64 float64209// DeserializeFloat64 deserializes a Float64.210func DeserializeFloat64(d []byte) (Float64, error) {211 buf := bytes.NewBuffer(d)212 var value float64213 if err := binary.Read(buf, binary.LittleEndian, &value); err != nil {214 return 0, essentials.AddCtx("deserialize float64", err)215 }216 return Float64(value), nil217}218// Serialize serializes the object.219func (f Float64) Serialize() ([]byte, error) {220 var buf bytes.Buffer221 binary.Write(&buf, binary.LittleEndian, float64(f))222 return buf.Bytes(), nil223}224// SerializerType returns the unique ID used to serialize225// a Float64.226func (f Float64) SerializerType() string {227 return "float64"228}229// Float32 is a Serializer for a float32.230type Float32 float32231// DeserializeFloat32 deserializes a Float32.232func DeserializeFloat32(d []byte) (Float32, error) {233 buf := bytes.NewBuffer(d)234 var value float32235 if err := binary.Read(buf, binary.LittleEndian, &value); err != nil {236 return 0, essentials.AddCtx("deserialize float32", err)237 }238 return Float32(value), nil239}240// Serialize serializes the object.241func (f Float32) Serialize() ([]byte, error) {242 var buf bytes.Buffer243 binary.Write(&buf, binary.LittleEndian, float32(f))244 return buf.Bytes(), nil245}246// SerializerType returns the unique ID used to serialize247// a Float64.248func (f Float32) SerializerType() string {249 return "float32"250}251// A Float64Slice is a Serializer for a []float64.252type Float64Slice []float64253// DeserializeFloat64Slice deserializes a Float64Slice.254func DeserializeFloat64Slice(d []byte) (Float64Slice, error) {255 reader := bytes.NewBuffer(d)256 var size uint64257 if err := binary.Read(reader, binary.LittleEndian, &size); err != nil {258 return nil, essentials.AddCtx("deserialize []float64", err)259 }260 vec := make([]float64, int(size))261 if err := binary.Read(reader, binary.LittleEndian, vec); err != nil {262 return nil, essentials.AddCtx("deserialize []float64", err)263 }264 return vec, nil265}266// Serialize serializes the object.267func (f Float64Slice) Serialize() ([]byte, error) {268 var w bytes.Buffer269 binary.Write(&w, binary.LittleEndian, uint64(len(f)))270 binary.Write(&w, binary.LittleEndian, []float64(f))271 return w.Bytes(), nil272}273// SerializerType returns the unique ID used to serialize274// a Float64Slice.275func (f Float64Slice) SerializerType() string {276 return "[]float64"277}278// A Float32Slice is a Serializer for a []float32.279type Float32Slice []float32280// DeserializeFloat32Slice deserializes a Float32Slice.281func DeserializeFloat32Slice(d []byte) (Float32Slice, error) {282 reader := bytes.NewBuffer(d)283 var size uint64284 if err := binary.Read(reader, binary.LittleEndian, &size); err != nil {285 return nil, essentials.AddCtx("deserialize []float32", err)286 }287 vec := make([]float32, int(size))288 if err := binary.Read(reader, binary.LittleEndian, vec); err != nil {289 return nil, essentials.AddCtx("deserialize []float32", err)290 }291 return vec, nil292}293// Serialize serializes the object.294func (f Float32Slice) Serialize() ([]byte, error) {295 var w bytes.Buffer296 binary.Write(&w, binary.LittleEndian, uint64(len(f)))297 binary.Write(&w, binary.LittleEndian, []float32(f))298 return w.Bytes(), nil299}300// SerializerType returns the unique ID used to serialize301// a Float32Slice.302func (f Float32Slice) SerializerType() string {303 return "[]float32"304}305// A Bool is a Serializer for a bool.306type Bool bool307// DeserializeBool deserializes a Bool.308func DeserializeBool(d []byte) (Bool, error) {309 if len(d) != 1 {310 return false, errors.New("deserialize bool: invalid length")311 }312 if d[0] == 0 {313 return false, nil314 } else if d[0] == 1 {315 return true, nil316 } else {317 return false, errors.New("deserialize bool: invalid value")318 }319}320// Serialize serializes the object.321func (b Bool) Serialize() ([]byte, error) {322 if b {323 return []byte{1}, nil324 } else {325 return []byte{0}, nil326 }327}328// SerializerType returns the unique ID used to serialize329// a Bool.330func (b Bool) SerializerType() string {331 return "bool"332}...
byte
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", 20}6 enc := gob.NewEncoder(&network)7 dec := gob.NewDecoder(&network)8 err := enc.Encode(p1)9 if err != nil {10 fmt.Println(err)11 }12 err = dec.Decode(&p2)13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(p2.Name)17 fmt.Println(p2.Age)18}
byte
Using AI Code Generation
1import (2type User struct {3}4func main() {5 u := User{6 }7 serializer := json.NewStream(json.NewConfig(), nil, nil)8 encoder := gotype.NewEncoder(serializer)9 if err := encoder.Encode(u); err != nil {10 panic(err)11 }12 fmt.Println(serializer.Bytes())13}
byte
Using AI Code Generation
1import (2func main() {3 data := map[string]interface{}{4 }5 enc := codec.NewEncoderBytes(&buf, &mh)6 enc.Encode(data)7 fmt.Println(buf)8 var out map[string]interface{}9 dec := codec.NewDecoderBytes(buf, &mh)10 dec.Decode(&out)11 fmt.Println(out)12}
byte
Using AI Code Generation
1import (2func main() {3 ser := Serializer{}4 f, err := os.OpenFile("test.txt", os.O_CREATE|os.O_RDWR, 0666)5 if err != nil {6 log.Fatal(err)7 }8 defer f.Close()9 _, err = f.WriteString("Hello World!")10 if err != nil {11 log.Fatal(err)12 }13 bytes, err := ioutil.ReadAll(f)14 if err != nil {15 log.Fatal(err)16 }17 ser.Deserialize(bytes)18 fmt.Println(ser)19}
byte
Using AI Code Generation
1import (2type person struct {3}4func main() {5 p1 := person{6 }7 p2 := person{8 }9 p3 := person{10 }11 p4 := person{12 }13 p5 := person{14 }15 p := []person{p1, p2, p3, p4, p5}16 fmt.Println(p)17 bs := encode(p)18 fmt.Println(bs)19 decode(bs)20 uuid, err := uuid.NewV4()21 if err != nil {22 log.Fatalln(err)23 }24 fmt.Println(uuid)25}26func encode(p []person) []byte {27 bs := make([]byte, 0)28 for _, v := range p {29 bs = append(bs, []byte(v.First)...)30 bs = append(bs, []byte(v.Last)...)31 }32}33func decode(bs []byte) {34 for i := 0; i < len(bs); i += 2 {35 p = append(p, person{First: string(bs[i]), Last: string(bs[i+1])})36 }37 fmt.Println(p)38}
byte
Using AI Code Generation
1import (2func main() {3 s := serializer.Serializer{}4 b := []byte("Hello World")5 s.Byte(b)6 fmt.Println("Byte method of serializer class")7 fmt.Println(b)8}
byte
Using AI Code Generation
1import (2func main() {3 person := &protobuf2.Person{4 }5 data, err := proto.Marshal(person)6 if err != nil {7 fmt.Println("Error in marshalling", err)8 }9 fmt.Println(data)10 newPerson := &protobuf2.Person{}11 err = proto.Unmarshal(data, newPerson)12 if err != nil {13 fmt.Println("Error in unmarshalling", err)14 }15 fmt.Println(newPerson.GetName())16 fmt.Println(newPerson.GetAge())17}
byte
Using AI Code Generation
1import (2func main() {3 test := &pb.Test{4 Label: proto.String("hello"),5 Type: proto.Int32(17),6 Reps: proto.Int64(10),7 }8 data, err := proto.Marshal(test)9 if err != nil {10 fmt.Println("marshaling error: ", err)11 }12 newTest := &pb.Test{}13 err = proto.Unmarshal(data, newTest)14 if err != nil {15 fmt.Println("unmarshaling error: ", err)16 }17 if test.GetLabel() != newTest.GetLabel() {18 fmt.Printf("data mismatch %q != %q\n", test.GetLabel(), newTest.GetLabel())19 } else {20 fmt.Println("Wrote ", test.GetLabel(), "Read ", newTest.GetLabel())21 }22}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!