134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
...
198
199
200
201
202
203
204
205
206
207
208
209
210
211
|
-- generic type constructors --
-------------------------------
function G.int(bits,signed)
local bytes = math.ceil(bits / 8)
local max = 2 ^ bits
local spoint = math.floor(max/2)
return {
sz = bytes;
name = string.format("%sint<%s>",
signed and 's' or 'u', bits
);
enc = function(obj)
obj = obj or 0
local val = math.abs(obj)
local str = ''
if signed then
local max = math.floor(max / 2)
if (obj > max) or (obj < (0-(max+1))) then
return m.err.domain end
if obj < 0 then val = val + spoint end
-- e.g. for 8bit: 0x80 == -1; 0xFF = -128
else
if val > max then return m.err.domain end
end
for i=1,bytes do
local n = math.fmod(val, 0x100)
str = str .. string.char(n)
val = math.floor(val / 0x100)
end
return str
................................................................................
def = ...
end
name = 'struct' .. (name and ':' .. name or '');
report('defining struct name=%q fields=%s', name, dump(def))
return {
name = name;
enc = function(obj)
local enc = m.streamEncoder()
local n = 0
for k,ty in pairs(def) do n=n+1
if obj[k] == nil then error('missing key '..dump(k)..' for type '..ty.name) end
local encoded = ty.enc(obj[k])
enc.push(T.u8.enc(#k), size.enc(#encoded), k, encoded)
end
|
|
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
-- generic type constructors --
-------------------------------
function G.int(bits,signed)
local bytes = math.ceil(bits / 8)
local max = 2 ^ bits
local spoint = math.floor(max/2)
local name = string.format("%sint<%s>",
signed and 's' or 'u', bits
);
return {
name = name;
sz = bytes;
enc = function(obj)
report('encoding %s value=%s', name, dump(obj))
obj = obj or 0
local val = math.abs(obj)
local str = ''
if signed then
local max = math.floor(max / 2)
if (obj > max) or (obj < (0-(max+1))) then
return error('domain error') end
if obj < 0 then val = val + spoint end
-- e.g. for 8bit: 0x80 == -1; 0xFF = -128
else
if val > max then error('domain error') end
end
for i=1,bytes do
local n = math.fmod(val, 0x100)
str = str .. string.char(n)
val = math.floor(val / 0x100)
end
return str
................................................................................
def = ...
end
name = 'struct' .. (name and ':' .. name or '');
report('defining struct name=%q fields=%s', name, dump(def))
return {
name = name;
enc = function(obj)
report('encoding struct name=%q vals=%s', name, dump(obj))
local enc = m.streamEncoder()
local n = 0
for k,ty in pairs(def) do n=n+1
if obj[k] == nil then error('missing key '..dump(k)..' for type '..ty.name) end
local encoded = ty.enc(obj[k])
enc.push(T.u8.enc(#k), size.enc(#encoded), k, encoded)
end
|