strict_types 2.9.1

Strict types: confined generalized algebraic data types (GADT)
Documentation
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Strict encoding schema library, implementing validation and parsing of strict encoded data
// against a schema.
//
// SPDX-License-Identifier: Apache-2.0
//
// Designed in 2019-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
// Written in 2024-2025 by Dr Maxim Orlovsky <orlovsky@ubideco.org>
//
// Copyright (C) 2022-2025 Laboratories for Ubiquitous Deterministic Computing (UBIDECO),
//                         Institute for Distributed and Cognitive Systems (InDCS), Switzerland.
// Copyright (C) 2022-2025 Dr Maxim Orlovsky.
// All rights under the above copyrights are reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under
// the License.

//! Reification module: reads & writes strict values from binary strict encodings.

use amplify::ascii::AsciiString;
use amplify::confinement::{
    Confined, LargeAscii, LargeBlob, LargeString, MediumAscii, MediumBlob, MediumString,
    SmallAscii, SmallBlob, SmallString, TinyAscii, TinyBlob, TinyString, U16 as MAX16,
    U32 as MAX32,
};
use amplify::num::{u24, u40, u48, u56};
use encoding::{DecodeError, Primitive, ReadRaw, StreamReader, StrictDecode, StrictReader};
use indexmap::IndexMap;

use crate::typesys::{SymbolicSys, TypeSymbol, UnknownType};
use crate::typify::{TypeSpec, TypedVal};
use crate::value::Blob;
use crate::{SemId, StrictVal, Ty, TypeRef, TypeSystem};

#[derive(Clone, Eq, PartialEq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum Error {
    /// unknown type `{0}`.
    TypeAbsent(TypeSpec),

    #[display(inner)]
    #[from]
    UnknownType(UnknownType),

    /// {0} is not yet implemented. Please update `strict_types` to the latest version.
    NotImplemented(String),

    #[display(inner)]
    #[from]
    Decode(DecodeError),

    /// data provided to reify operation are not entirely consumed during deserialization.
    NotEntirelyConsumed,
}

impl SymbolicSys {
    pub fn strict_deserialize_type(
        &self,
        spec: impl Into<TypeSpec>,
        data: &[u8],
    ) -> Result<TypedVal, Error> {
        let spec = spec.into();
        let sem_id = self.to_sem_id(spec.clone()).ok_or(Error::TypeAbsent(spec))?;
        self.as_types().strict_deserialize_type(sem_id, data)
    }

    pub fn strict_read_type(
        &self,
        spec: impl Into<TypeSpec>,
        d: &mut impl ReadRaw,
    ) -> Result<TypedVal, Error> {
        let spec = spec.into();
        let sem_id = self.to_sem_id(spec.clone()).ok_or(Error::TypeAbsent(spec))?;
        self.as_types().strict_read_type(sem_id, d)
    }
}

impl TypeSystem {
    fn strict_read_list(
        &self,
        len: usize,
        ty: SemId,
        d: &mut impl ReadRaw,
    ) -> Result<Vec<StrictVal>, Error> {
        let mut list = Vec::with_capacity(len);
        for _ in 0..len {
            let item = self.strict_read_type(ty, d)?;
            list.push(item.val);
        }
        Ok(list)
    }

    fn strict_read_map(
        &self,
        len: usize,
        key_ty: SemId,
        ty: SemId,
        d: &mut impl ReadRaw,
    ) -> Result<Vec<(StrictVal, StrictVal)>, Error> {
        let mut list = Vec::with_capacity(len);
        for _ in 0..len {
            let key = self.strict_read_type(key_ty, d)?;
            let item = self.strict_read_type(ty, d)?;
            list.push((key.val, item.val));
        }
        Ok(list)
    }

    pub fn strict_deserialize_type(&self, sem_id: SemId, data: &[u8]) -> Result<TypedVal, Error> {
        let mut cursor = StreamReader::cursor::<MAX32>(data);
        let ty = self.strict_read_type(sem_id, &mut cursor)?;
        if cursor.unconfine().position() as usize != data.len() {
            return Err(Error::NotEntirelyConsumed);
        }
        Ok(ty)
    }

    pub fn strict_read_type(
        &self,
        sem_id: SemId,
        mut d: &mut impl ReadRaw,
    ) -> Result<TypedVal, Error> {
        let spec = TypeSpec::from(sem_id);
        let ty = self.find(sem_id).ok_or_else(|| Error::TypeAbsent(spec.clone()))?;

        let mut reader = StrictReader::with(d);

        let val = match ty {
            Ty::Primitive(prim) => {
                match *prim {
                    Primitive::UNIT => StrictVal::Unit,
                    Primitive::BYTE => StrictVal::num(u8::strict_decode(&mut reader)?),
                    Primitive::U8 => StrictVal::num(u8::strict_decode(&mut reader)?),
                    Primitive::U16 => StrictVal::num(u16::strict_decode(&mut reader)?),
                    Primitive::U24 => StrictVal::num(u24::strict_decode(&mut reader)?.into_u32()),
                    Primitive::U32 => StrictVal::num(u32::strict_decode(&mut reader)?),
                    Primitive::U40 => StrictVal::num(u40::strict_decode(&mut reader)?),
                    Primitive::U48 => StrictVal::num(u48::strict_decode(&mut reader)?),
                    Primitive::U56 => StrictVal::num(u56::strict_decode(&mut reader)?),
                    Primitive::U64 => StrictVal::num(u64::strict_decode(&mut reader)?),
                    // Primitive::U128 => StrictVal::num(u128::strict_decode(&mut reader)?),
                    Primitive::I8 => StrictVal::num(i8::strict_decode(&mut reader)?),
                    Primitive::I16 => StrictVal::num(i16::strict_decode(&mut reader)?),
                    // I24 => StrictVal::num(i24::strict_decode(&mut reader)?),
                    Primitive::I32 => StrictVal::num(i32::strict_decode(&mut reader)?),
                    Primitive::I64 => StrictVal::num(i64::strict_decode(&mut reader)?),
                    // Primitive::I128 => StrictVal::num(i128::strict_decode(&mut reader)?),
                    other => {
                        return Err(Error::NotImplemented(format!(
                            "loading {other} into a typed value is not yet implemented"
                        )));
                    }
                }
            }
            Ty::UnicodeChar => {
                todo!()
            }

            // ASCII strings:
            Ty::List(sem_id, sizing)
                if self
                    .find(*sem_id)
                    .ok_or_else(|| Error::TypeAbsent(spec.clone()))?
                    .is_char_enum() =>
            {
                if sizing.max <= u8::MAX as u64 {
                    StrictVal::String(TinyAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u16::MAX as u64 {
                    StrictVal::String(SmallAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u24::MAX.into_u64() {
                    StrictVal::String(MediumAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u32::MAX as u64 {
                    StrictVal::String(LargeAscii::strict_decode(&mut reader)?.to_string())
                } else {
                    StrictVal::String(
                        Confined::<AsciiString, 0, { u64::MAX as usize }>::strict_decode(
                            &mut reader,
                        )?
                        .to_string(),
                    )
                }
            }
            // Restricted strings:
            Ty::Tuple(fields) if self.is_rstring(fields)? => {
                let (_, sizing) = self.rstring_sizing(fields)?.expect("checked in match");
                if sizing.max <= u8::MAX as u64 {
                    StrictVal::String(TinyAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u16::MAX as u64 {
                    StrictVal::String(SmallAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u24::MAX.into_u64() {
                    StrictVal::String(MediumAscii::strict_decode(&mut reader)?.to_string())
                } else if sizing.max <= u32::MAX as u64 {
                    StrictVal::String(LargeAscii::strict_decode(&mut reader)?.to_string())
                } else {
                    StrictVal::String(
                        Confined::<AsciiString, 0, { u64::MAX as usize }>::strict_decode(
                            &mut reader,
                        )?
                        .to_string(),
                    )
                }
            }

            Ty::Enum(variants) => {
                let tag = u8::strict_decode(&mut reader)?;
                let Some(name) = variants.name_by_tag(tag) else {
                    return Err(DecodeError::EnumTagNotKnown(spec.to_string(), tag).into());
                };
                StrictVal::enumer(name.clone())
            }
            Ty::Union(variants) => {
                let tag = u8::strict_decode(&mut reader)?;
                let Some((variant, ty)) = variants.by_tag(tag) else {
                    return Err(DecodeError::EnumTagNotKnown(spec.to_string(), tag).into());
                };
                let fields = self.strict_read_type(*ty, reader.unbox())?;
                StrictVal::union(variant.name.clone(), fields.val)
            }
            Ty::Tuple(reqs) => {
                let mut fields = Vec::with_capacity(reqs.len());
                let d = reader.unbox();
                for ty in reqs {
                    let checked = self.strict_read_type(*ty, d)?;
                    fields.push(checked.val);
                }
                StrictVal::tuple(fields)
            }
            Ty::Struct(reqs) => {
                let mut fields = IndexMap::with_capacity(reqs.len());
                let d = reader.unbox();
                for field in reqs {
                    let checked = self.strict_read_type(field.ty, d)?;
                    fields.insert(field.name.clone(), checked.val);
                }
                StrictVal::Struct(fields)
            }

            // Fixed-size arrays:
            Ty::Array(ty, len) if ty.is_byte() => {
                let d = reader.unbox();
                let buf = d.read_raw::<MAX16>(*len as usize).map_err(DecodeError::from)?;
                StrictVal::Bytes(Blob(buf))
            }
            Ty::Array(ty, len) => {
                let mut list = Vec::<StrictVal>::with_capacity(*len as usize);
                let d = reader.unbox();
                for _ in 0..*len {
                    let checked = self.strict_read_type(*ty, d)?;
                    list.push(checked.val);
                }
                StrictVal::List(list)
            }

            // Byte strings:
            Ty::List(ty, sizing) if ty.is_byte() && sizing.max <= u8::MAX as u64 => {
                let string = TinyBlob::strict_decode(&mut reader)?;
                StrictVal::Bytes(Blob(string.release()))
            }
            Ty::List(ty, sizing) if ty.is_byte() && sizing.max <= u16::MAX as u64 => {
                let string = SmallBlob::strict_decode(&mut reader)?;
                StrictVal::Bytes(Blob(string.release()))
            }
            Ty::List(ty, sizing) if ty.is_byte() && sizing.max <= u24::MAX.into_u64() => {
                let string = MediumBlob::strict_decode(&mut reader)?;
                StrictVal::Bytes(Blob(string.release()))
            }
            Ty::List(ty, sizing) if ty.is_byte() && sizing.max <= u32::MAX as u64 => {
                let string = LargeBlob::strict_decode(&mut reader)?;
                StrictVal::Bytes(Blob(string.release()))
            }

            // Unicode strings:
            Ty::List(ty, sizing) if ty.is_unicode_char() && sizing.max <= u8::MAX as u64 => {
                let string = TinyString::strict_decode(&mut reader)?;
                StrictVal::String(string.release())
            }
            Ty::List(ty, sizing) if ty.is_unicode_char() && sizing.max <= u16::MAX as u64 => {
                let string = SmallString::strict_decode(&mut reader)?;
                StrictVal::String(string.release())
            }
            Ty::List(ty, sizing) if ty.is_unicode_char() && sizing.max <= u24::MAX.into_u64() => {
                let string = MediumString::strict_decode(&mut reader)?;
                StrictVal::String(string.release())
            }
            Ty::List(ty, sizing) if ty.is_unicode_char() && sizing.max <= u32::MAX as u64 => {
                let string = LargeString::strict_decode(&mut reader)?;
                StrictVal::String(string.release())
            }

            // Other lists:
            Ty::List(ty, sizing) if sizing.max <= u8::MAX as u64 => {
                let len = u8::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::List(list)
            }
            Ty::List(ty, sizing) if sizing.max <= u16::MAX as u64 => {
                let len = u16::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::List(list)
            }
            Ty::List(ty, sizing) if sizing.max <= u24::MAX.into_u64() => {
                let len = u24::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len.into_usize(), *ty, d)?;
                StrictVal::List(list)
            }
            Ty::List(ty, sizing) if sizing.max <= u32::MAX as u64 => {
                let len = u32::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::List(list)
            }
            Ty::List(ty, _) => {
                let len = u64::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::List(list)
            }
            // TODO: Find a way to check for the uniqueness of the set values
            Ty::Set(ty, sizing) if sizing.max <= u8::MAX as u64 => {
                let len = u8::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::Set(list)
            }
            Ty::Set(ty, sizing) if sizing.max <= u16::MAX as u64 => {
                let len = u16::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::Set(list)
            }
            Ty::Set(ty, sizing) if sizing.max <= u24::MAX.into_u64() => {
                let len = u24::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len.into_usize(), *ty, d)?;
                StrictVal::Set(list)
            }
            Ty::Set(ty, sizing) if sizing.max <= u32::MAX as u64 => {
                let len = u32::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::Set(list)
            }
            Ty::Set(ty, _) => {
                let len = u64::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_list(len as usize, *ty, d)?;
                StrictVal::Set(list)
            }
            Ty::Map(key_id, id, sizing) if sizing.max <= u8::MAX as u64 => {
                let len = u8::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_map(len as usize, *key_id, *id, d)?;
                StrictVal::Map(list)
            }
            Ty::Map(key_id, id, sizing) if sizing.max <= u16::MAX as u64 => {
                let len = u16::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_map(len as usize, *key_id, *id, d)?;
                StrictVal::Map(list)
            }
            Ty::Map(key_id, id, sizing) if sizing.max <= u24::MAX.into_u64() => {
                let len = u24::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_map(len.into_usize(), *key_id, *id, d)?;
                StrictVal::Map(list)
            }
            Ty::Map(key_id, id, sizing) if sizing.max <= u32::MAX as u64 => {
                let len = u32::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_map(len as usize, *key_id, *id, d)?;
                StrictVal::Map(list)
            }
            Ty::Map(key_id, id, _sizing) => {
                let len = u64::strict_decode(&mut reader)?;
                d = reader.unbox();
                let list = self.strict_read_map(len as usize, *key_id, *id, d)?;
                StrictVal::Map(list)
            }
        };

        Ok(TypedVal {
            val,
            orig: TypeSymbol::unnamed(sem_id),
        })
    }
}

#[cfg(test)]
mod test {
    use super::super::test_helpers::*;
    // use super::*;

    #[test]
    fn typify() {
        let sys = test_system();
        //let nominal = Nominal::with("TICK", "Some name", 2);
        let value = ston!(name "Some name", ticker "TICK", precision svenum!(2));
        let checked = sys.typify(value, "TestLib.Nominal").unwrap();
        assert_eq!(
            format!("{}", checked.val),
            r#"name "Some name", ticker "TICK", precision twoDecimals"#
        );
    }
}