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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use compact_str::CompactString;
use core::{cmp::Ordering, hash::Hasher, num::NonZeroU32, ops::ControlFlow};
use primitive_enum::FromU8;
use rapira::{byte_rapira, Rapira, RapiraError};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use std::collections::HashSet;
#[cfg(feature = "std")]
use thiserror::Error;
use twox_hash::XxHash32;

use crate::{Datetime, Value};

fn is_uniq_sorted(mut iter: impl Iterator<Item = u32>) -> Ordering {
    let first = iter.next();
    match first {
        Some(first) => {
            let is_uniq = iter.try_fold(first, |acc, item| match acc.cmp(&item) {
                Ordering::Less => ControlFlow::Continue(item),
                Ordering::Equal => ControlFlow::Break(Ordering::Equal),
                Ordering::Greater => ControlFlow::Break(Ordering::Greater),
            });
            match is_uniq {
                ControlFlow::Continue(_) => Ordering::Less,
                ControlFlow::Break(ordering) => ordering,
            }
        }
        None => Ordering::Less,
    }
}

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
pub struct NamedField {
    pub name: CompactString,
    pub typ: Scheme,
}

type FieldsArr<T> = SmallVec<[T; 4]>;

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
#[serde(tag = "type", content = "data")]
pub enum Fields {
    // named fields must be unique
    Named(FieldsArr<NamedField>),
    Unnamed(FieldsArr<Scheme>),
}

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
pub struct StructType {
    pub fields: Fields,
}

impl StructType {
    pub fn check_bytes(
        &self,
        slice: &mut &[u8],
        types: &[StoredType<IdWithPath>],
    ) -> rapira::Result<()> {
        match &self.fields {
            Fields::Named(named) => named
                .iter()
                .try_for_each(|item| item.typ.check_bytes(slice, types)),
            Fields::Unnamed(unnamed) => unnamed
                .iter()
                .try_for_each(|item| item.check_bytes(slice, types)),
        }
    }

    pub fn check_scheme(&self) -> Result<(), SchemeError> {
        match &self.fields {
            Fields::Named(named) => {
                let mut uniq = HashSet::with_capacity(named.len());

                if !named.iter().all(|n| uniq.insert(&n.name)) {
                    Err(SchemeError::OtherError)
                } else {
                    Ok(())
                }
            }
            Fields::Unnamed(_) => Ok(()),
        }
    }
}

// variants must be sorted
type Variants<T> = SmallVec<[(u16, T); 4]>;

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
pub struct EnumType {
    pub variants: Variants<NamedField>,
}

// enum with variant number and name
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug, Rapira)]
pub struct SimpleEnum {
    pub variants: Variants<CompactString>,
}

pub type PathArr = SmallVec<[CompactString; 2]>;

pub trait Ident {}

#[derive(PartialEq, Eq, Clone, Debug, Rapira, Serialize, Deserialize)]
pub struct TypePath(PathArr);

impl Ident for TypePath {}

#[derive(PartialEq, Eq, Clone, Copy, Debug, Rapira, Serialize, Deserialize)]
#[repr(transparent)]
pub struct TypeId(NonZeroU32);

impl Ident for TypeId {}

#[derive(PartialEq, Eq, Clone, Debug, Rapira, Serialize, Deserialize)]
pub struct IdWithPath {
    // user id or auto generated id
    pub id: NonZeroU32,
    // at least 1 item should be for type name
    pub path: PathArr,
}

impl Ident for IdWithPath {}

#[derive(PartialEq, Eq, Clone, Copy, Debug, Rapira, Serialize, Deserialize)]
pub struct IndexedId {
    pub id: NonZeroU32,
    pub index: u32,
}

#[derive(PartialEq, Eq, Clone, Copy, Debug, Rapira, Serialize, Deserialize, FromU8)]
#[repr(u8)]
pub enum TypeIdent {
    Id,
    Path,
    IdWithPath,
}

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
#[repr(u8)]
pub enum ComplexType {
    SimpleEnum(SimpleEnum),
    Struct(StructType),
    Enum(EnumType),
}

impl ComplexType {
    pub fn check_scheme(&mut self) -> Result<(), SchemeError> {
        match self {
            ComplexType::SimpleEnum(simple) => {
                let ord = is_uniq_sorted(simple.variants.iter().map(|v| v.0 as u32));
                match ord {
                    Ordering::Less => Ok(()),
                    Ordering::Equal => Err(SchemeError::OtherError),
                    Ordering::Greater => {
                        simple.variants.sort_unstable_by_key(|v| v.0);
                        let ord = is_uniq_sorted(simple.variants.iter().map(|v| v.0 as u32));
                        if !matches!(ord, Ordering::Less) {
                            Err(SchemeError::OtherError)
                        } else {
                            Ok(())
                        }
                    }
                }
            }
            ComplexType::Struct(s) => s.check_scheme(),
            ComplexType::Enum(e) => {
                let ord = is_uniq_sorted(e.variants.iter().map(|v| v.0 as u32));
                match ord {
                    Ordering::Less => Ok(()),
                    Ordering::Equal => Err(SchemeError::OtherError),
                    Ordering::Greater => {
                        e.variants.sort_unstable_by_key(|v| v.0);
                        let ord = is_uniq_sorted(e.variants.iter().map(|v| v.0 as u32));
                        if !matches!(ord, Ordering::Less) {
                            Err(SchemeError::OtherError)
                        } else {
                            Ok(())
                        }
                    }
                }
            }
        }
    }
}

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
pub struct StoredType<T: Ident> {
    ident: T,
    typ: ComplexType,
}

#[derive(PartialEq, Clone, Serialize, Deserialize, Debug, Rapira)]
#[serde(tag = "type", content = "data")]
#[rapira(static_size = "None")]
#[repr(u8)]
pub enum Scheme {
    Void,
    Bool,
    U8,
    U16,
    U32,
    U64,
    I32,
    I64,
    F32,
    F64,
    Decimal,
    Datetime,
    Str,
    // need?
    ID,
    // like json, dynamic data
    Dynamic,
    // массив байт
    // Bytes,
    // массив байт фиксированного размера
    // array bytes with bytes count in scheme
    // ArrayBytes(u32),
    // max array size?
    Array(u32, Box<Scheme>),
    // Вектор или массив значений одного типа
    Vec(Box<Scheme>),
    Optional(Box<Scheme>),
    // embedded struc type, like item: {a: "b"} in typescript or tuple ("b", 1)
    Struct(Box<StructType>),
    Stored(IndexedId),
}

#[cfg_attr(feature = "std", derive(Error, Debug))]
pub enum SchemeError {
    #[cfg_attr(feature = "std", error("type not found"))]
    TypeNotFound,
    #[cfg_attr(feature = "std", error("deserialize error"))]
    DeserializeError,
    #[cfg_attr(feature = "std", error("identifications error"))]
    IdentsError,
    #[cfg_attr(feature = "std", error("rapira error"))]
    RapiraError(#[from] RapiraError),
    #[cfg_attr(feature = "std", error("other error"))]
    OtherError,
}

impl Scheme {
    pub fn is_stored(&self) -> bool {
        match self {
            Scheme::Array(_, inner) => inner.is_stored(),
            Scheme::Vec(inner) => inner.is_stored(),
            Scheme::Optional(inner) => inner.is_stored(),
            Scheme::Struct(struct_type) => match &struct_type.fields {
                Fields::Named(named) => named.iter().any(|item| item.typ.is_stored()),
                Fields::Unnamed(unnamed) => unnamed.iter().any(|item| item.is_stored()),
            },
            Scheme::Stored(_) => true,
            _ => false,
        }
    }

    pub fn init_stored(&mut self, ids: &[NonZeroU32]) -> Result<(), SchemeError> {
        match self {
            Scheme::Array(_, inner) => inner.init_stored(ids),
            Scheme::Vec(inner) => inner.init_stored(ids),
            Scheme::Optional(inner) => inner.init_stored(ids),
            Scheme::Struct(struct_type) => match &mut struct_type.fields {
                Fields::Named(named) => named
                    .iter_mut()
                    .try_for_each(|item| item.typ.init_stored(ids)),
                Fields::Unnamed(unnamed) => unnamed
                    .iter_mut()
                    .try_for_each(|item| item.init_stored(ids)),
            },
            Scheme::Stored(typ) => ids
                .binary_search(&typ.id)
                .map(|index| {
                    typ.index = index as u32;
                })
                .map_err(|_| SchemeError::TypeNotFound),
            _ => Ok(()),
        }
    }

    #[inline]
    pub fn check_bytes(
        &self,
        slice: &mut &[u8],
        types: &[StoredType<IdWithPath>],
    ) -> Result<(), RapiraError> {
        match self {
            Scheme::Void => Ok(()),
            Scheme::Bool => bool::check_bytes(slice),
            Scheme::U8 => byte_rapira::check_bytes::<()>(slice),
            Scheme::U16 => u16::check_bytes(slice),
            Scheme::U32 => u32::check_bytes(slice),
            Scheme::U64 => u64::check_bytes(slice),
            Scheme::I32 => i32::check_bytes(slice),
            Scheme::I64 => i64::check_bytes(slice),
            Scheme::F32 => f32::check_bytes(slice),
            Scheme::F64 => f64::check_bytes(slice),
            Scheme::Decimal => Decimal::check_bytes(slice),
            Scheme::Datetime => Datetime::check_bytes(slice),
            Scheme::Str => String::check_bytes(slice),
            Scheme::ID => NonZeroU32::check_bytes(slice),
            Scheme::Dynamic => Value::check_bytes(slice),
            Scheme::Array(n, s) => (0u32..*n).try_for_each(|_| s.check_bytes(slice, types)),
            Scheme::Vec(s) => {
                let size = u32::from_slice(slice)?;
                (0u32..size).try_for_each(|_| s.check_bytes(slice, types))
            }
            Scheme::Optional(s) => {
                let exist = bool::from_slice(slice)?;
                if exist {
                    s.check_bytes(slice, types)
                } else {
                    Ok(())
                }
            }
            Scheme::Struct(s) => s.check_bytes(slice, types),
            Scheme::Stored(stored) => match types.get(stored.index as usize) {
                Some(ty) => match &ty.typ {
                    ComplexType::SimpleEnum(simple) => {
                        let variant = byte_rapira::from_slice(slice)? as u16;
                        if !simple.variants.iter().any(|i| i.0 == variant) {
                            Err(RapiraError::EnumVariantError)
                        } else {
                            Ok(())
                        }
                    }
                    ComplexType::Struct(s) => s.check_bytes(slice, types),
                    ComplexType::Enum(e) => {
                        let variant = byte_rapira::from_slice(slice)? as u16;
                        let variant = e.variants.iter().find(|i| i.0 == variant);
                        match variant {
                            Some((_, NamedField { typ, .. })) => typ.check_bytes(slice, types),
                            None => Err(RapiraError::EnumVariantError),
                        }
                    }
                },
                None => Err(RapiraError::IterNextError),
            },
        }
    }
}

/*
Во первых проверяем что нет дубликатов путей.
Для этого просто нужно где то регистрировать коллекции.
А может наоборот, пусть внешний код передает в иерархической форме данные?
Тогда по сути не должно быть повторений.

Во вторых создаем для каждого пути свой id в некой коллекции.
То есть у нас будет что-то типа Map<Id, StoredType>
Где Id - генерируется на основе пути? Или просто порядковый номер?
Если брать хеш функцию, то нужна постоянная, чтобы хранить значение в БД.
Можно просто массив значений с их индексом?

И в третьих если нужны будут миграции, нужно как то сопоставлять старую схему и новую.
Так же нужно предусмотреть возможность изменения названий и путей типов данных, но сохраняя саму структуру.
То есть если пользователь отправит ту же структуру, но с другим path, нужно изменить его id (или нет?), изменить все структуры, которые используют его id на новый, но миграцию не делать. Schema-only migration.

Или делать id на основе самого типа, брать хеш от него? Тогда не нужно будет менять id везде. Или как еще?
Нет, для этого можно создать отдельную функцию компаратор, для сравнения по значениям, чтобы пропускать переименование полей.

Можно генерировать уникальные постоянные (которые генерируют одинаковые id для одинаковых данных) ключи, или можно сортировать типы данных, чтобы была всегда однородность обработки типов.
*/
pub fn parse_scheme(
    bytes: &[u8],
    scheme: &[u8],
    is_enumerated: bool,
) -> Result<(Scheme, Vec<StoredType<IdWithPath>>), SchemeError> {
    let mut new_types: Vec<StoredType<IdWithPath>> =
        rapira::deserialize(bytes).map_err(|_| SchemeError::DeserializeError)?;
    let mut scheme: Scheme =
        rapira::deserialize(scheme).map_err(|_| SchemeError::DeserializeError)?;

    // order
    if is_enumerated {
        let ord = is_uniq_sorted(new_types.iter().map(|item| item.ident.id.get()));
        match ord {
            Ordering::Less => {}
            Ordering::Equal => return Err(SchemeError::IdentsError),
            Ordering::Greater => {
                new_types.sort_unstable_by_key(|item| item.ident.id);
                let ord = is_uniq_sorted(new_types.iter().map(|item| item.ident.id.get()));
                if !matches!(ord, Ordering::Less) {
                    return Err(SchemeError::OtherError);
                }
            }
        }
    } else {
        for StoredType { ident, typ: _ } in &mut new_types {
            let full_path = ident.path.join("");
            let mut hasher = XxHash32::default();
            hasher.write(full_path.as_bytes());
            let hash = hasher.finish() as u32;

            ident.id = NonZeroU32::new(hash).ok_or(SchemeError::IdentsError)?;
        }

        new_types.sort_unstable_by_key(|item| item.ident.id);
    }

    // check scheme
    new_types
        .iter_mut()
        .try_for_each(|item| item.typ.check_scheme())?;

    let ids: Vec<NonZeroU32> = new_types.iter().map(|i| i.ident.id).collect();
    let len = new_types.len();
    let mut iter = new_types.into_iter();

    let types: Vec<StoredType<IdWithPath>> =
        iter.try_fold(Vec::with_capacity(len), |mut acc, mut new_type| {
            let item = match &mut new_type.typ {
                ComplexType::SimpleEnum(_) => new_type,
                ComplexType::Struct(struct_type) => match &mut struct_type.fields {
                    Fields::Named(named) => {
                        for item in named {
                            item.typ.init_stored(&ids)?;
                        }
                        new_type
                    }
                    Fields::Unnamed(unnamed) => {
                        for item in unnamed {
                            item.init_stored(&ids)?;
                        }
                        new_type
                    }
                },
                ComplexType::Enum(enum_type) => {
                    for (_, variant) in &mut enum_type.variants {
                        variant.typ.init_stored(&ids)?;
                    }
                    new_type
                }
            };
            acc.push(item);
            Ok(acc) as Result<Vec<StoredType<IdWithPath>>, SchemeError>
        })?;

    scheme.init_stored(&ids)?;

    Ok((scheme, types))
}