Skip to content

Commit e3ff491

Browse files
committed
Binary entity (de)-serialization
1 parent fbf486d commit e3ff491

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## [[unpublished]](https://github.com/mlange-42/ark/compare/v0.6.4...v0.6.5)
4+
5+
### Features
6+
7+
- Provides binary serialization and de-serialization of entities for networking (#453)
8+
39
## [[v0.6.4]](https://github.com/mlange-42/ark/compare/v0.6.3...v0.6.4)
410

511
### Bugfixes

ecs/entity.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package ecs
22

33
import (
4+
"encoding/binary"
45
"encoding/json"
6+
"fmt"
57
"reflect"
68
)
79

@@ -82,6 +84,26 @@ func (e *Entity) UnmarshalJSON(data []byte) error {
8284
return nil
8385
}
8486

87+
// MarshalBinary returns a binary representation of the entity, for serialization and networking purposes.
88+
func (e *Entity) MarshalBinary() []byte {
89+
buf := make([]byte, 8)
90+
binary.BigEndian.PutUint32(buf[0:4], uint32(e.id))
91+
binary.BigEndian.PutUint32(buf[4:8], e.gen)
92+
return buf
93+
}
94+
95+
// UnmarshalBinary into an entity.
96+
//
97+
// For serialization and networking purposes only. Do not use this to create entities!
98+
func (e *Entity) UnmarshalBinary(data []byte) error {
99+
if len(data) != 8 {
100+
return fmt.Errorf("invalid data length: expected 8 bytes, got %d", len(data))
101+
}
102+
e.id = entityID(binary.BigEndian.Uint32(data[0:4]))
103+
e.gen = binary.BigEndian.Uint32(data[4:8])
104+
return nil
105+
}
106+
85107
// entityIndex denotes an entity's location by table and row index.
86108
type entityIndex struct {
87109
table tableID

ecs/entity_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,23 @@ func TestEntityMarshal(t *testing.T) {
5050
err = e2.UnmarshalJSON([]byte("pft"))
5151
expectNotNil(t, err)
5252
}
53+
54+
func TestEntityMarshalBinary(t *testing.T) {
55+
e := Entity{2, 3}
56+
57+
binData, err := json.Marshal(&e)
58+
if err != nil {
59+
t.Fatal(err)
60+
}
61+
62+
e2 := Entity{}
63+
err = json.Unmarshal(binData, &e2)
64+
if err != nil {
65+
t.Fatal(err)
66+
}
67+
68+
expectEqual(t, e2, e)
69+
70+
err = e2.UnmarshalJSON(make([]byte, 9))
71+
expectNotNil(t, err)
72+
}

0 commit comments

Comments
 (0)