Revert "Revert "Made use of ::= in core libraries and defined a RebindError condition...
[cslatevm.git] / src / lib / struct.slate
blob94b30f099441ce2cc63022e14fb851edf6c1bafb
2 "provides similar functionality to python's struct.pack"
4 lobby define: #StructMixin &parents: {Cloneable} &slots: {#binaryDescription -> ExtensibleArray new}.
6 "binaryDescription is a list of (slotName type), e.g. (width Int32)"
8 struct@(StructMixin traits) littleEndian
10   OverrideThis
13 struct@(StructMixin traits) packed &littleEndian: le
15   le `defaultsTo: struct littleEndian.
16   [| :out |
17    struct binaryDescription do:
18      [| :slotDescription type slot |
19       slot := slotDescription first.
20       type := slotDescription second.
21       ({#Int8 ->  [| :x | out next: 1 putInteger: x &littleEndian: le].
22         #Int16 -> [| :x | out next: 2 putInteger: x &littleEndian: le].
23         #Int32 -> [| :x | out next: 4 putInteger: x &littleEndian: le].
24         #Int64 -> [| :x | out next: 8 putInteger: x &littleEndian: le].
25         #CString -> [| :x | out ; (x as: out collectionType). out nextPut: 0].
26         #ByteArray -> [| :x | out ; x].
27         #Fixed -> [| :x | out ; (x as: out collectionType)].
28         #Struct -> [| :x | out ; (x packed &littleEndian: le)].
29        } firstSatisfying: [| :each | each key = type])
30         ifNil: [error: 'Could find method to serialize ' ; slotDescription printString]
31         ifNotNilDo: [| :found | found value applyWith:
32                                   (found key = #Fixed ifTrue: [slot] ifFalse: [struct atSlotNamed: slot])]]
33   ] writingAs: ByteArray