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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
/*-
 * shm-rs - a scheme serialization lib
 * Copyright (C) 2021  Aleksandr Morozov
 * 
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use core::fmt;
use std::borrow::Borrow;
use std::rc::Rc;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};

use crate::common::{global_variable_rust_lex, format_string_len};
use crate::serializator::serializator::Structure;
use crate::static_throw_text;

use super::error::StaticSchemeError;
use super::scheme::{VectorSerializType, GenericDataTypes};

/// Contains a data type which is used to describe the field of the
/// struct or enum.
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum RustCodeItemDataType
{
    /// (width of the int)
    Uint(u64),
    /// (width of the int)
    Int(u64),
    Bool,
    String,
    Struct(String),
    Enum(String),
    Vector(Box<RustCodeItemDataType>, VectorSerializType),
    Range(Box<RustCodeItemDataType>),
    RangeInclusive(Box<RustCodeItemDataType>),
    AnyType
}

impl fmt::Display for RustCodeItemDataType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::Uint(w) => write!(f, "u{}", w*8),
            Self::Int(w) => write!(f, "i{}", w*8),
            Self::Bool => write!(f, "bool"),
            Self::String => write!(f, "String"),
            Self::Struct(ref s) => write!(f, "{}", s),
            Self::Enum(ref e) => write!(f, "{}", e),
            Self::Vector(ref v, vst) => 
            {
                match vst
                {
                    VectorSerializType::Array => write!(f, "Vec<{}>", v),
                    VectorSerializType::Hashset => write!(f, "std::collections::HashSet<{}>", v),
                    VectorSerializType::Indexset => write!(f, "indexmap::IndexSet<{}>", v)
                }
                
            },
            Self::Range(ref r) => write!(f, "Range<{}>", r),
            Self::RangeInclusive(ref r) => write!(f, "RangeInclusive<{}>", r),
            Self::AnyType => write!(f, "{}", RustCode::ANY_TYPE_ENUM)
        }
        
    }
}

/// A field of the structure.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct RustCodeItemStruct
{
    field_name: Option<String>,
    field_opt: bool,
    field_datatype: RustCodeItemDataType
}

impl fmt::Display for RustCodeItemStruct
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        if self.field_opt == true
        {        
            write!(f, "{}: Option<{}>", self.field_name.as_ref().unwrap_or(&"Anonymous".to_string()), self.field_datatype)
        }
        else
        {
            write!(f, "{}: {}", self.field_name.as_ref().unwrap_or(&"Anonymous".to_string()), self.field_datatype)
        }
    }
}


impl RustCodeItemStruct
{
    pub 
    fn new(field_name: Option<&String>, field_opt: bool, field_datatype: RustCodeItemDataType) -> Self
    {
        return 
            Self{ field_name: field_name.map(|m| m.clone()).clone(), field_opt, field_datatype };
    }
}

/// A type of the enum.
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum RustCodeEnumType
{
    /// A enum which does not have inner data. (1 - comment)
    Empty(String, Option<String>),
    /// A list of inner types.
    Vector(String, Vec<RustCodeItemDataType>, Option<String>),
    /// A structured inner type.
    Fields(String, Vec<RustCodeItemStruct>, Option<String>)
}

impl RustCodeEnumType
{
    pub 
    fn new_anon(title: &String, comment: Option<String>) -> Self
    {
        return Self::Empty(title.clone(), comment);
    }

    pub 
    fn new_vec(title: &String, items: Vec<RustCodeItemDataType>, comment: Option<String>) -> Self
    {
        return 
            Self::Vector(title.clone(), items, comment);
    }

    pub 
    fn new_fields(title: &String, items: Vec<RustCodeItemStruct>, comment: Option<String>) -> Self
    {
        return 
            Self::Fields(title.clone(), items, comment);
    }
}

impl fmt::Display for RustCodeEnumType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            RustCodeEnumType::Empty(ref title, ref comment) =>
            {
                if let Some(com) = comment
                {
                    write!(f, "    {}\n", format_string_len(com, 80, "///"))?;
                }

                write!(f, "    {}", title)
            },
            RustCodeEnumType::Vector(ref title, ref items, ref comment) => 
            {
                if let Some(com) = comment
                {
                    write!(f, "    {}\n", format_string_len(com, 80, "///"))?;
                }

                write!(f, "    {}(", title)?;

                for (item, itemno) in items.iter().zip(0..items.len())
                {
                    write!(f, "{}", item)?;

                    if itemno+1 != items.len()
                    {
                        write!(f, ", ")?;
                    }
                }

                write!(f, ")")
            },
            RustCodeEnumType::Fields(ref title, ref fields, ref comment) => 
            {
                if let Some(com) = comment
                {
                    write!(f, "    {}\n", format_string_len(com, 80, "///"))?;
                }

                write!(f, "    {}{{ ", title)?;

                for (field, fieldno) in fields.iter().zip(0..fields.len())
                {
                    write!(f, "{}", field)?;

                    if fieldno+1 != fields.len()
                    {
                        write!(f, ", ")?;
                    }
                }

                write!(f, " }}")
            }
        }
    }
}


/// A difinition for the public constant values (defines).
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum RustCodeDefineType
{
    String(String),
    Int(i64),
    Uint(u64),
    LongInt(i128),
    LongUInt(u128),
    Bool(bool),
}


impl fmt::Display for RustCodeDefineType
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::String(ref s) => 
                write!(f, "&'static str = \"{}\"", s),
            Self::Int(ref i) => 
                write!(f, "i64 = {}", i),
            Self::Uint(ref u) => 
                write!(f, "u64 = {}", u),
            Self::LongInt(ref i) => 
                write!(f, "i128 = {}",  i),
            Self::LongUInt(ref u) => 
                write!(f, "u128 = {}",  u),
            Self::Bool(ref b) => 
                write!(f, "bool = {}", b),
        }
    }
}

impl TryFrom<&GenericDataTypes> for RustCodeDefineType
{
    type Error = StaticSchemeError;

    fn try_from(value: &GenericDataTypes) -> Result<Self, Self::Error> 
    {
        match *value
        {
            GenericDataTypes::Boolean(ref b, _) => 
                Ok(Self::Bool(*b)),
            GenericDataTypes::Int(ref i, _) => 
                Ok(Self::Int(*i)),
            GenericDataTypes::UInt(ref u, _) => 
                Ok(Self::Uint(*u)),
            GenericDataTypes::LongInt(ref i, _) =>
                Ok(Self::LongInt(*i)),
            GenericDataTypes::LongUInt(ref u, _) =>
                Ok(Self::LongUInt(*u)),
            GenericDataTypes::String(ref s, _) => 
                Ok(Self::String(s.clone())),
            GenericDataTypes::None => 
                static_throw_text!("can not convert generic type: '{}' to \
                    RustCodeDefineType, unknown type", value),
            GenericDataTypes::Symbol(_, li) |
            GenericDataTypes::Variable(_, li) |
            GenericDataTypes::Entity(_, li) |
            GenericDataTypes::Enumerator(_, _, li) |
            GenericDataTypes::Vector(_, li) |
            GenericDataTypes::Range(_, _, li) |
            GenericDataTypes::RangeIncl(_, _, li) |
            GenericDataTypes::AnyValWrap(_, li) => 
                static_throw_text!("can not convert generic type: '{}' to \
                    RustCodeDefineType, unknown type, at: '{}'", value, li),
            
        }
    }
}

/// An instance type on the list.
#[derive(Clone, Eq, PartialEq, Hash)]
pub enum RustCodeItem
{
    Enumerator{ title: String, enum_type: Vec<RustCodeEnumType>, comment: Option<String> },
    Struct{ title: String, fields: Vec<RustCodeItemStruct>, is_root: bool, comment: Option<String> },
    Define{ title: String, value: RustCodeDefineType},
}

impl fmt::Display for RustCodeItem
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match *self
        {
            Self::Enumerator{ ref title, ref enum_type, .. } => 
            {
                write!(f, "pub enum {} \n{{ \n", title)?;

                // print enum items
                for (enm, enmno) 
                in enum_type.iter().zip(0..enum_type.len())
                {
                    write!(f, "{}", enm)?;

                    if enmno+1 != enum_type.len()
                    {
                        write!(f, ", \n")?;
                    }

                    write!(f, "\n")?;
                }

                writeln!(f, "}}\n")
            },
            Self::Struct{ ref title, ref fields, .. } => 
            {
                write!(f, "pub struct {} \n{{ \n", title)?;

                for (field, fieldno) 
                in fields.iter().zip(0..fields.len())
                {
                    write!(f, "    pub {}", field)?;

                    if fieldno+1 != fields.len()
                    {
                        writeln!(f, ",")?;
                    }
                    else
                    {
                        writeln!(f, "")?;
                    }
                }

                writeln!(f, "}}\n")
            },
            Self::Define{ ref title, ref value } =>
            {
                writeln!(f, "pub const {}: {};", global_variable_rust_lex(title), value)
            }   
        }
    }
}

impl RustCodeItem
{
    pub 
    fn is_enum(&self) -> bool
    {
        match *self
        {
            Self::Enumerator { .. } => return true,
            Self::Struct { .. } => return false,
            Self::Define { .. } => return false,
        }
    }

    pub 
    fn get_comment(&self) -> Option<&String>
    {
        match *self
        {
            Self::Enumerator { ref comment, .. } => return comment.as_ref(),
            Self::Struct { ref comment, .. } => return comment.as_ref(),
            Self::Define { .. } => return None,
        }
    }

    pub 
    fn is_define(&self) -> bool
    {
        return 
            std::mem::discriminant(self) == 
                std::mem::discriminant(
                    &Self::Define { title: String::new(), value: RustCodeDefineType::Bool(false) }
                );
    }

    pub 
    fn get_title(&self) -> &str
    {
        match *self
        {
            Self::Enumerator{ ref title, .. } => return title.as_str(),
            Self::Struct{ ref title, .. } => return title.as_str(),
            Self::Define { ref title, .. } => return title.as_str(),
        }
    }

    pub 
    fn new_struct(strk: Rc<Structure>, items: Vec<RustCodeItemStruct>, is_root: bool) -> Self
    {
        return 
            Self::Struct
            { 
                title: strk.get_struct_name().get_name_1().to_string(), 
                fields: items, 
                is_root: is_root, 
                comment: strk.get_comment().map_or(None, |v| Some(v.clone())),
            };
    }

    pub 
    fn new_enum(title: &str, items: Vec<RustCodeEnumType>, commnent: Option<&String>) -> Self
    {
        return 
            Self::Enumerator
            {
                 title: title.to_string(), 
                 enum_type: items,
                 comment: commnent.map_or(None, |v| Some(v.clone())),
            };
    }

    pub 
    fn new_define(title: &str, value: RustCodeDefineType) -> Self
    {
        return 
            Self::Define { title: title.to_string(), value: value };
    }
}

/*
impl Hash for RustCodeItem
{
    fn hash<H: Hasher>(&self, state: &mut H) 
    {
        match *self
        {
            RustCodeItem::Enumerator { ref title, ref enum_type } => 
            {
                title.hash(state);
                enum_type.hash(state);
            },
            RustCodeItem::Struct { ref title, ref fields, ref is_root } => 
            {
                title.hash(state);
                fields.hash(state);
                is_root.hash(state);
            },
        }
        
    }
}
*/

/// A struct which defines a `#[derive]` for a specific struct/enum.
/// The item is searched by name of the item.
pub struct RustCodeDerivRepl
{
    /// name of the struct/enum
    item_title: String,

    /// a new derives
    deriv_items: Vec<String>,
}

impl Hash for RustCodeDerivRepl
{
    fn hash<H: Hasher>(&self, state: &mut H) 
    {
        self.item_title.hash(state);
    }
}

impl Eq for RustCodeDerivRepl {}

impl PartialEq for RustCodeDerivRepl 
{
    fn eq(&self, other: &Self) -> bool 
    {
        return 
            self.item_title == other.item_title;
    }
}

impl Borrow<String> for RustCodeDerivRepl
{
    fn borrow(&self) -> &String
    {
        return &self.item_title;
    }
}

impl Borrow<str> for RustCodeDerivRepl
{
    fn borrow(&self) -> &str
    {
        return self.item_title.as_str();
    }
}


impl RustCodeDerivRepl
{
    pub 
    fn new(item_title: &str, deriv_items: &[&'static str]) -> Self
    {
        return 
            Self
            { 
                item_title: item_title.to_string(), 
                deriv_items: deriv_items.into_iter().map(|d| d.to_string()).collect() 
            };
    }

    pub 
    fn form_derive(&self) -> String
    {
        return self.deriv_items.join(", ");
    }
}

/// A root instance which contains generated items and static 
/// information to generate the rust structs/enums.
pub struct RustCode
{
    /// A generated structs/enums from scheme file.
    items: Vec<RustCodeItem>,

    /// A \#\[derive()\] items for enum.
    deriv_enum: &'static [&'static str],

    /// A \#\[derive()\] items for struct.
    deriv_struct: &'static [&'static str],

    /// A override of the \#\[derive()\] for the enum/struct by its name
    deriv_repl: HashSet<RustCodeDerivRepl>,

    /// A path to the serde crate (use ...)
    serde_path: &'static str,

    /// A serde configuration of the path (#[serde(crate = "")]).
    /// Use if reexported from somewhere.
    serde_crate_path: Option<&'static str>,

    /// A 'use' path to the file with collected structs i,e super::structs::common
    common_file_usepath: Option<&'static str>,

    /// Is set to true if field with any type presents
    is_any_type_present: bool
}

impl fmt::Display for RustCode
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        writeln!(f, "use {};\n", self.serde_path)?;

        if self.common_file_usepath.is_some() == true
        {
            writeln!(f, "use {}::*;\n\n", self.common_file_usepath.as_ref().unwrap())?;
        }

        for item in self.items.iter()
        {
            if item.is_define() == false
            {
                if let Some(com) = item.get_comment()
                {
                    write!(f, "{} \n", format_string_len(com, 80, "///"))?;
                }

                if let Some(der) = self.deriv_repl.get(item.get_title())
                {
                    writeln!(f, "#[derive({})]", der.form_derive())?;
                }
                else
                {
                    if item.is_enum() == true
                    {
                        writeln!(f, "#[derive({})]", self.deriv_enum.join(", "))?;
                    }
                    else
                    {
                        writeln!(f, "#[derive({})]", self.deriv_struct.join(", "))?;
                    }
                }

                if let Some(ref path) = self.serde_crate_path
                {
                    writeln!(f, "#[serde(crate = \"{}\")]", path)?;
                }
            }

            writeln!(f, "{}", item)?
        }

        return Ok(());
    }
}


impl RustCode
{
    pub const SERDE_PATH: &'static str = "serde::{Serialize, Deserialize}";
    pub const ANY_TYPE_ENUM: &'static str = "ShmTypeAnyField";

    pub const ANY_TYPE_ENUM_STR: &'static str = "String";
    pub const ANY_TYPE_ENUM_ENTITY: &'static str = "Entity";
    pub const ANY_TYPE_ENUM_VARIABLE: &'static str = "Variable";
    pub const ANY_TYPE_ENUM_UINT: &'static str = "UInt";
    pub const ANY_TYPE_ENUM_LONGUINT: &'static str = "LongUInt";
    pub const ANY_TYPE_ENUM_INT: &'static str = "Int";
    pub const ANY_TYPE_ENUM_LONGINT: &'static str = "LongInt";
    pub const ANY_TYPE_ENUM_BOOL: &'static str = "Bool";

    pub
    fn new(deriv_enum: &'static [&'static str], deriv_struct: &'static [&'static str]) -> Self
    {
        return 
            Self
            {
                items: Vec::new(),
                deriv_enum: deriv_enum,
                deriv_struct: deriv_struct,
                deriv_repl: HashSet::new(),
                serde_path: Self::SERDE_PATH,
                serde_crate_path: None,
                common_file_usepath: None,
                is_any_type_present: false,
            };
    }

    pub 
    fn overide_serde_path(&mut self, ser_path: &'static str)
    {
        self.serde_path = ser_path;
    }

    pub 
    fn overide_serde_crate_path(&mut self, ser_crate_path: &'static str)
    {
        self.serde_crate_path = Some(ser_crate_path);
    }

    pub 
    fn add_derive_override(&mut self, item: RustCodeDerivRepl)
    {
        self.deriv_repl.insert(item);
    }

    pub(crate)
    fn add_item(&mut self, item: RustCodeItem)
    {
        for i in self.items.iter()
        {
            if i.get_title() == item.get_title()
            {
                return;
            }
        }
        self.items.push(item);
        
        return;
    }

    /// Self locking function which sets the flag `is_any_type_present` and 
    /// creates an enumerator which defines types.
    pub(crate)
    fn set_field_any(&mut self, int_width: u64)
    {
        if self.is_any_type_present == false
        {
            self.is_any_type_present = true;

            self.add_item(
                RustCodeItem::new_enum(
                    Self::ANY_TYPE_ENUM, 
                    vec![
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_INT.to_string(), 
                            vec![RustCodeItemDataType::Int(int_width)], 
                            Some("An integer data type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_UINT.to_string(), 
                            vec![RustCodeItemDataType::Uint(int_width)],
                            Some("An unsigned integer type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_LONGINT.to_string(), 
                            vec![RustCodeItemDataType::Int(int_width)], 
                            Some("An integer data type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_LONGUINT.to_string(), 
                            vec![RustCodeItemDataType::Uint(int_width)],
                            Some("An unsigned integer type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_BOOL.to_string(), 
                            vec![RustCodeItemDataType::Bool],
                            Some("A boolean type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_STR.to_string(), 
                            vec![RustCodeItemDataType::String],
                            Some("A string type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_ENTITY.to_string(), 
                            vec![RustCodeItemDataType::String],
                            Some("An entity type".to_string())
                        ),
                        RustCodeEnumType::new_vec(
                            &Self::ANY_TYPE_ENUM_VARIABLE.to_string(), 
                            vec![RustCodeItemDataType::String],
                            Some("A variable type".to_string())
                        ),
                    ],
                    Some(&"An enum for the auto type".to_string())
                )
            )
        }
    }
}

impl RustCode
{
    /// A static method which can be used to search for the common strucutures/enums in 
    /// generated Rust code. A structures and enums are searched by its title and
    /// its content. All found common structures are removed from the instances and
    /// returned in [RustCode] instance. The [RustCodeDerivRepl] and `serde_path` and 
    /// `serde_crate_path` are not derived. It is possible to set it later.
    /// 
    /// # Arguments
    /// 
    /// * `common_file_usepath` - a [str] path to the location with common structures.
    ///     i.e super::structs::common_structs where `common_structs` is a rs file.
    /// 
    /// * `items` - a [Vec] with mut references to initialized instances of [RustCode] 
    ///     where the common structs will be searched.
    /// 
    /// * `deriv_enum` - an array with items for `#[derive]` for enum.
    /// 
    /// * `deriv_struct - an array with items for `#[derive]` for structs.
    /// 
    /// # Returns
    /// 
    /// An [Option] is returned where:
    /// 
    /// * [Some] is returned with instance
    /// 
    /// * [None] is returned if no repeating structures/enums where found.
    pub 
    fn search_common(
        common_file_usepath: &'static str,
        mut items: Vec<&mut RustCode>,
        deriv_enum: &'static [&'static str], 
        deriv_struct: &'static [&'static str]
    ) -> Option<RustCode>
    {
        let mut hash_items: HashSet<&RustCodeItem> = HashSet::new();
        let mut intersections: HashSet<RustCodeItem> = HashSet::new();

        for itm in items.iter()
        {
            // convert to hashset
            let inner: HashSet<&RustCodeItem> = 
                itm.items.iter().map(|n| n).collect();


            if hash_items.len() > 0
            {
                // perform an intersection on two hashsets
                let intersection: HashSet<RustCodeItem> = 
                    hash_items.intersection(&inner).map(|n| (*n).clone()).collect();
             
                // extend the list of intersections, don't care about repeating
                intersections.extend(intersection);
            }
            
            // fill the common list
            hash_items.extend(inner);
        }

        // removing a common structs
        for itm in items.iter_mut()
        {
            let len = itm.items.len();

            itm.items.retain(|it| 
                {
                    for intrs in intersections.iter()
                    {
                        if intrs == it
                        {
                            return false;
                        }
                    }

                    return true;
                }
            );

            // if something was removed then add a `use` to file with common structs/enums.
            if itm.items.len() < len
            {
                itm.common_file_usepath = Some(common_file_usepath);
            }
        }

        if intersections.len() > 0
        {
            let mut commons = RustCode::new(deriv_enum, deriv_struct);
            //commons.common_file_usepath = Some(common_file_usepath);
            
            // copy 
            commons.items.extend(intersections);

            return Some(commons);
        }
        else
        {
            return None;
        }
        
    }
}