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
use crate::representations::*;
use crate::rust::prelude::*;
use crate::traversal::*;
use crate::*;

#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(tag = "type") // See https://serde.rs/enum-representations.html
)]
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
pub enum NoCustomValueKind {}

#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(tag = "type") // See https://serde.rs/enum-representations.html
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoCustomValue {}

impl CustomValue<NoCustomValueKind> for NoCustomValue {
    fn get_custom_value_kind(&self) -> NoCustomValueKind {
        panic!("No custom value")
    }
}

pub type BasicEncoder<'a> = VecEncoder<'a, NoCustomValueKind>;
pub type BasicDecoder<'a> = VecDecoder<'a, NoCustomValueKind>;
pub type BasicTraverser<'a> = VecTraverser<'a, NoCustomTraversal>;
pub type BasicValue = Value<NoCustomValueKind, NoCustomValue>;
pub type BasicValueKind = ValueKind<NoCustomValueKind>;

// 5b for (basic) [5b]or - (90 in decimal)
pub const BASIC_SBOR_V1_PAYLOAD_PREFIX: u8 = 0x5b;
pub const BASIC_SBOR_V1_MAX_DEPTH: usize = 64;

// The following trait "aliases" are to be used in parameters.
//
// They are much nicer to read than the underlying traits, but because they are "new", and are defined
// via blanket impls, they can only be used for parameters, but cannot be used for implementations.
//
// Implementations should instead implement the underlying traits:
// * Categorize<X> (impl over all X: CustomValueKind)
// * Encode<X, E> (impl over all X: CustomValueKind, E: Encoder<X>)
// * Decode<X, D> (impl over all X: CustomValueKind, D: Decoder<X>)
//
// TODO: Change these to be Trait aliases once stable in rust: https://github.com/rust-lang/rust/issues/41517
pub trait BasicCategorize: Categorize<NoCustomValueKind> {}
impl<T: Categorize<NoCustomValueKind> + ?Sized> BasicCategorize for T {}

pub trait BasicSborEnum: SborEnum<NoCustomValueKind> {}
impl<T: SborEnum<NoCustomValueKind> + ?Sized> BasicSborEnum for T {}

pub trait BasicSborTuple: SborTuple<NoCustomValueKind> {}
impl<T: SborTuple<NoCustomValueKind> + ?Sized> BasicSborTuple for T {}

pub trait BasicDecode: for<'a> Decode<NoCustomValueKind, BasicDecoder<'a>> {}
impl<T: for<'a> Decode<NoCustomValueKind, BasicDecoder<'a>>> BasicDecode for T {}

pub trait BasicEncode: for<'a> Encode<NoCustomValueKind, BasicEncoder<'a>> {}
impl<T: for<'a> Encode<NoCustomValueKind, BasicEncoder<'a>> + ?Sized> BasicEncode for T {}

pub trait BasicDescribe: for<'a> Describe<NoCustomTypeKind> {}
impl<T: Describe<NoCustomTypeKind> + ?Sized> BasicDescribe for T {}

pub trait BasicSbor: BasicCategorize + BasicDecode + BasicEncode + BasicDescribe {}
impl<T: BasicCategorize + BasicDecode + BasicEncode + BasicDescribe> BasicSbor for T {}

/// Encode a `T` into byte array.
pub fn basic_encode<T: BasicEncode + ?Sized>(v: &T) -> Result<Vec<u8>, EncodeError> {
    basic_encode_with_depth_limit(v, BASIC_SBOR_V1_MAX_DEPTH)
}

pub fn basic_encode_with_depth_limit<T: BasicEncode + ?Sized>(
    v: &T,
    depth_limit: usize,
) -> Result<Vec<u8>, EncodeError> {
    let mut buf = Vec::with_capacity(512);
    let encoder = BasicEncoder::new(&mut buf, depth_limit);
    encoder.encode_payload(v, BASIC_SBOR_V1_PAYLOAD_PREFIX)?;
    Ok(buf)
}

/// Decode an instance of `T` from a slice.
pub fn basic_decode<T: BasicDecode>(buf: &[u8]) -> Result<T, DecodeError> {
    basic_decode_with_depth_limit(buf, BASIC_SBOR_V1_MAX_DEPTH)
}

pub fn basic_decode_with_depth_limit<T: BasicDecode>(
    buf: &[u8],
    depth_limit: usize,
) -> Result<T, DecodeError> {
    BasicDecoder::new(buf, depth_limit).decode_payload(BASIC_SBOR_V1_PAYLOAD_PREFIX)
}

impl CustomValueKind for NoCustomValueKind {
    fn as_u8(&self) -> u8 {
        panic!("No custom type")
    }

    fn from_u8(_id: u8) -> Option<Self> {
        None
    }
}

impl<X: CustomValueKind, E: Encoder<X>> Encode<X, E> for NoCustomValue {
    fn encode_value_kind(&self, _encoder: &mut E) -> Result<(), EncodeError> {
        panic!("No custom value")
    }

    fn encode_body(&self, _encoder: &mut E) -> Result<(), EncodeError> {
        panic!("No custom value")
    }
}

impl<X: CustomValueKind, D: Decoder<X>> Decode<X, D> for NoCustomValue {
    fn decode_body_with_value_kind(_: &mut D, _: ValueKind<X>) -> Result<Self, DecodeError>
    where
        Self: Sized,
    {
        panic!("No custom value")
    }
}

#[derive(Copy, Debug, Clone, PartialEq, Eq)]
pub enum NoCustomTerminalValueRef {}

impl CustomTerminalValueRef for NoCustomTerminalValueRef {
    type CustomValueKind = NoCustomValueKind;

    fn custom_value_kind(&self) -> Self::CustomValueKind {
        unreachable!("NoCustomTerminalValueRef can't exist")
    }
}

#[derive(Copy, Debug, Clone, PartialEq, Eq)]
pub enum NoCustomTraversal {}

impl CustomTraversal for NoCustomTraversal {
    type CustomValueKind = NoCustomValueKind;
    type CustomTerminalValueRef<'de> = NoCustomTerminalValueRef;

    fn decode_custom_value_body<'de, R>(
        _custom_value_kind: Self::CustomValueKind,
        _reader: &mut R,
    ) -> Result<Self::CustomTerminalValueRef<'de>, DecodeError>
    where
        R: BorrowingDecoder<'de, Self::CustomValueKind>,
    {
        unreachable!("NoCustomTraversal can't exist")
    }
}

/// Creates a payload traverser from the buffer
pub fn basic_payload_traverser<'b>(buf: &'b [u8]) -> BasicTraverser<'b> {
    BasicTraverser::new(
        buf,
        BASIC_SBOR_V1_MAX_DEPTH,
        ExpectedStart::PayloadPrefix(BASIC_SBOR_V1_PAYLOAD_PREFIX),
        true,
    )
}

#[derive(Debug, Clone, PartialEq, Eq, Sbor)]
pub enum NoCustomTypeKind {}

#[derive(Debug, Clone, PartialEq, Eq, Sbor)]
pub enum NoCustomTypeValidation {}

impl CustomTypeValidation for NoCustomTypeValidation {}

impl<L: SchemaTypeLink> CustomTypeKind<L> for NoCustomTypeKind {
    type CustomTypeValidation = NoCustomTypeValidation;
}

lazy_static::lazy_static! {
    static ref EMPTY_SCHEMA: Schema<NoCustomSchema> = {
        Schema::empty()
    };
}

#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum NoCustomSchema {}

impl CustomSchema for NoCustomSchema {
    type CustomTypeKind<L: SchemaTypeLink> = NoCustomTypeKind;
    type CustomTypeValidation = NoCustomTypeValidation;

    fn linearize_type_kind(
        _: Self::CustomTypeKind<RustTypeId>,
        _: &IndexSet<TypeHash>,
    ) -> Self::CustomTypeKind<LocalTypeId> {
        unreachable!("No custom type kinds exist")
    }

    fn resolve_well_known_type(
        well_known_id: WellKnownTypeId,
    ) -> Option<&'static TypeData<Self::CustomTypeKind<LocalTypeId>, LocalTypeId>> {
        WELL_KNOWN_LOOKUP
            .get(well_known_id.as_index())
            .and_then(|x| x.as_ref())
    }

    fn validate_custom_type_validation(
        _: &SchemaContext,
        _: &Self::CustomTypeKind<LocalTypeId>,
        _: &Self::CustomTypeValidation,
    ) -> Result<(), SchemaValidationError> {
        unreachable!("No custom type validation")
    }

    fn validate_custom_type_kind(
        _: &SchemaContext,
        _: &Self::CustomTypeKind<LocalTypeId>,
    ) -> Result<(), SchemaValidationError> {
        unreachable!("No custom type kinds exist")
    }

    fn validate_type_metadata_with_custom_type_kind(
        _: &SchemaContext,
        _: &Self::CustomTypeKind<LocalTypeId>,
        _: &TypeMetadata,
    ) -> Result<(), SchemaValidationError> {
        unreachable!("No custom type kinds exist")
    }

    fn empty_schema() -> &'static Schema<Self> {
        &EMPTY_SCHEMA
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum NoCustomExtension {}

create_well_known_lookup!(
    WELL_KNOWN_LOOKUP,
    well_known_basic_custom_types,
    NoCustomTypeKind,
    []
);

impl CustomExtension for NoCustomExtension {
    const PAYLOAD_PREFIX: u8 = BASIC_SBOR_V1_PAYLOAD_PREFIX;
    type CustomValueKind = NoCustomValueKind;
    type CustomTraversal = NoCustomTraversal;
    type CustomSchema = NoCustomSchema;

    fn custom_value_kind_matches_type_kind(
        _: &Schema<Self::CustomSchema>,
        _: Self::CustomValueKind,
        _: &TypeKind<
            <Self::CustomSchema as CustomSchema>::CustomTypeKind<LocalTypeId>,
            LocalTypeId,
        >,
    ) -> bool {
        unreachable!("No custom value kinds exist")
    }

    fn custom_type_kind_matches_non_custom_value_kind(
        _: &Schema<Self::CustomSchema>,
        _: &<Self::CustomSchema as CustomSchema>::CustomTypeKind<LocalTypeId>,
        _: ValueKind<Self::CustomValueKind>,
    ) -> bool {
        unreachable!("No custom type kinds exist")
    }
}

pub type BasicRawPayload<'a> = RawPayload<'a, NoCustomExtension>;
pub type BasicOwnedRawPayload = RawPayload<'static, NoCustomExtension>;
pub type BasicRawValue<'a> = RawValue<'a, NoCustomExtension>;
pub type BasicOwnedRawValue = RawValue<'static, NoCustomExtension>;
pub type BasicTypeKind<L> = TypeKind<NoCustomTypeKind, L>;
pub type BasicSchema = Schema<NoCustomSchema>;
pub type BasicVersionedSchema = VersionedSchema<NoCustomSchema>;
pub type BasicTypeData<L> = TypeData<NoCustomTypeKind, L>;

impl<'a> CustomDisplayContext<'a> for () {
    type CustomExtension = NoCustomExtension;
}

impl FormattableCustomExtension for NoCustomExtension {
    type CustomDisplayContext<'a> = ();

    fn display_string_content<'s, 'de, 'a, 't, 's1, 's2, F: fmt::Write>(
        _: &mut F,
        _: &Self::CustomDisplayContext<'a>,
        _: &<Self::CustomTraversal as CustomTraversal>::CustomTerminalValueRef<'de>,
    ) -> Result<(), fmt::Error> {
        unreachable!("No custom values exist")
    }
}

impl ValidatableCustomExtension<()> for NoCustomExtension {
    fn apply_validation_for_custom_value<'de>(
        _: &Schema<Self::CustomSchema>,
        _: &<Self::CustomTraversal as CustomTraversal>::CustomTerminalValueRef<'de>,
        _: LocalTypeId,
        _: &(),
    ) -> Result<(), PayloadValidationError<Self>> {
        unreachable!("No custom values exist")
    }

    fn apply_custom_type_validation_for_non_custom_value<'de>(
        _: &Schema<Self::CustomSchema>,
        _: &<Self::CustomSchema as CustomSchema>::CustomTypeValidation,
        _: &TerminalValueRef<'de, Self::CustomTraversal>,
        _: &(),
    ) -> Result<(), PayloadValidationError<Self>> {
        unreachable!("No custom type validationss exist")
    }
}

#[cfg(feature = "serde")]
mod serde_serialization {
    use super::*;

    impl SerializableCustomExtension for NoCustomExtension {
        fn map_value_for_serialization<'s, 'de, 'a, 't, 's1, 's2>(
            _: &SerializationContext<'s, 'a, Self>,
            _: LocalTypeId,
            _: <Self::CustomTraversal as CustomTraversal>::CustomTerminalValueRef<'de>,
        ) -> CustomTypeSerialization<'a, 't, 'de, 's1, 's2, Self> {
            unreachable!("No custom values exist")
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::rust::prelude::*;
    use crate::{
        basic_decode_with_depth_limit, basic_encode_with_depth_limit, BasicValue, BasicValueKind,
    };

    #[test]
    fn depth_counting() {
        // DEPTH(vec![]) = 1
        // * 1 => Vec
        //
        // DEPTH(vec![1u32]) = 2
        // * 1 => Vec
        // * 2 => u32

        let depth1 = BasicValue::Array {
            element_value_kind: BasicValueKind::U32,
            elements: vec![],
        };
        let depth2 = BasicValue::Array {
            element_value_kind: BasicValueKind::U32,
            elements: vec![BasicValue::U32 { value: 1 }],
        };

        // encode
        assert!(basic_encode_with_depth_limit(&depth1, 0).is_err());
        assert!(basic_encode_with_depth_limit(&depth1, 1).is_ok());
        assert!(basic_encode_with_depth_limit(&depth1, 2).is_ok());
        assert!(basic_encode_with_depth_limit(&depth2, 0).is_err());
        assert!(basic_encode_with_depth_limit(&depth2, 1).is_err());
        assert!(basic_encode_with_depth_limit(&depth2, 2).is_ok());

        let buffer1 = basic_encode_with_depth_limit(&depth1, 128).unwrap();
        let buffer2 = basic_encode_with_depth_limit(&depth2, 128).unwrap();

        // decode
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer1, 0).is_err());
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer1, 1).is_ok());
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer1, 2).is_ok());
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer2, 0).is_err());
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer2, 1).is_err());
        assert!(basic_decode_with_depth_limit::<Vec<u32>>(&buffer2, 2).is_ok());
    }
}