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
/*!
Accessor and extension traits for fields.
*/

use crate::std_::marker::PhantomData;

use crate::{
    mut_ref::MutRef,
    type_level::TStringSet,
    Structural,
    StructuralDyn,
};


mod tuple_impls;
mod most_impls;
pub mod multi_fields;


use self::multi_fields::{
    GetMultiField,
    GetMultiFieldMut,
};



/// Allows accessing the `FieldName` field.
///
/// `FieldName` represents the name of the field on the type level,
/// It is a type because a `FIELD_NAME:&'static str` const parameter 
/// was neither stable nor worked in nightly at the time this was defined.
///
/// # Usage as Bound Example
///
/// This example demonstrates how you can use this trait as a bound.
///
/// If you have a lot of field accessor bounds you could use `structural_alias` macro
/// to alias those bounds and use that alias instead.
///
/// ```rust
/// use structural::{GetField,GetFieldExt,TI,ti};
/// 
/// fn formatted_value<T,S>(this:&T)->String
/// where
///     T:GetField<TI!(v a l u e), Ty=S>,
///     S:std::fmt::Debug,
/// {
///     format!("{:#?}",this.field_(ti!(value)) )
/// }
///
/// #[derive(structural::Structural)]
/// struct Huh<T>{
///     #[struc(access="mut")]
///     value:T,
/// }
/// 
/// fn main(){
///     let this=Huh{value:"Hello, World!"};
///     assert!( formatted_value(&this).contains("Hello, World!") );
/// }
///
/// ```
///
/// # Manual Implementation Example
///
/// While this trait is intended to be implemented using the `Structural` derive macro,
/// you can manually implement it like this:
///
/// ```rust
/// use structural::{
///     GetField,Structural,TI,TList,
///     structural_trait::{FieldInfo,TField},
///     impl_structural_dyn,
/// };
///
/// struct Huh<T>{
///     value:T,
/// }
///
/// impl<T> Structural for Huh<T>{
///     const FIELDS:&'static[FieldInfo]=&[FieldInfo::not_renamed("value")];
///     
///     type Fields=TList![ TField<TI!(v a l u e),T> ];
/// }
///
/// impl_structural_dyn!{ impl[T] Huh<T> }
///
/// impl<T> GetField<TI!(v a l u e)> for Huh<T>{
///     type Ty=T;
///
///     fn get_field_(&self)->&Self::Ty{
///         &self.value
///     }
/// }
///
///
/// ```
///
pub trait GetField<FieldName>:StructuralDyn{
    /// The type of the `FieldName` field.
    type Ty;

    /// Accesses the `FieldName` field by reference.
    fn get_field_(&self)->&Self::Ty;
}


/// Queries the type of a field.
///
/// # Example
///
/// Here is one way you can get the type of a field.
///
/// ```
/// use structural::{GetField,GetFieldExt,GetFieldType,TI,ti};
///
/// fn get_name<T>(this:&T)->&GetFieldType<T,TI!(n a m e)>
/// where
///     T:GetField<TI!(n a m e)>
/// {
///     this.field_(ti!(name))
/// }
///
///
/// #[derive(structural::Structural)]
/// struct Huh<T>{
///     #[struc(public)]
///     #[struc(rename="name")]
///     value:T,
/// }
///
/// fn main(){
///     let this=Huh{ value:"ooh".to_string() };
///     
///     assert_eq!( get_name(&this), "ooh" );
/// }
/// ```
/// 
/// Another way `get_name` could have been written is like this:
///
/// ```
/// use structural::{GetField,GetFieldExt,GetFieldType,TI,ti};
///
/// fn get_name<T,O>(this:&T)->&O
/// where
///     T:GetField<TI!(n a m e), Ty=O>
/// {
///     this.field_(ti!(name))
/// }
/// ```
/// A potential downside of adding another type parameter is that it 
/// makes it less ergonomic to specify the type of `T` while ignoring the field type,
/// since one has to write it as `get_name::<Foo,_>(&foo)`.
/// 
///
pub type GetFieldType<This,FieldName>=<This as GetField<FieldName>>::Ty;


/// Allows accessing the `FieldName` field mutably.
///
/// # Usage as Bound Example
///
/// This example demonstrates how you can use this trait as a bound.
///
/// If you have a lot of field accessor bounds you could use `structural_alias` macro
/// to alias those bounds and use that alias instead.
///
/// ```rust
/// use structural::{GetFieldMut,GetFieldExt,TI,ti};
/// 
/// fn take_value<T,V>(this:&mut T)->V
/// where
///     T:GetFieldMut<TI!(v a l u e), Ty=V>,
///     V:Default,
/// {
///     std::mem::replace( this.field_mut(ti!(value)), Default::default() )
/// }
///
/// #[derive(structural::Structural)]
/// struct Huh<T>{
///     #[struc(access="mut")]
///     value:T,
/// }
/// 
/// fn main(){
///     let mut this=Huh{value:"Hello, World!"};
///     assert_eq!(take_value(&mut this),"Hello, World!");
///     assert_eq!(this.value,"");
/// }
///
/// ```
///
/// # Manual Implementation Example
///
/// While this trait is intended to be implemented using the `Structural` derive macro,
/// you can manually implement it like this:
///
/// ```rust
/// use structural::{
///     GetField,GetFieldMut,Structural,TI,TList,
///     structural_trait::{FieldInfo,TField},
///     mut_ref::MutRef,
///     impl_structural_dyn,
/// };
///
/// struct Huh<T>{
///     value:T,
/// }
///
/// impl<T> Structural for Huh<T>{
///     const FIELDS:&'static[FieldInfo]=&[FieldInfo::not_renamed("value")];
///
///     type Fields=TList![ TField<TI!(v a l u e),T> ];
/// }
///
/// impl_structural_dyn!{ impl[T] Huh<T> }
///
/// impl<T> GetField<TI!(v a l u e)> for Huh<T>{
///     type Ty=T;
///
///     fn get_field_(&self)->&Self::Ty{
///         &self.value
///     }
/// }
///
/// unsafe impl<T> GetFieldMut<TI!(v a l u e)> for Huh<T>{
///     fn get_field_mut_(&mut self)->&mut Self::Ty{
///         &mut self.value
///     }
///     structural::unsafe_impl_get_field_raw_mut_method!{
///         Self,
///         field_name=value,
///         name_generic=TI!(v a l u e)
///     }
/// }
///
/// ```
///
pub unsafe trait GetFieldMut<FieldName>:GetField<FieldName>{
    /// Accesses the `FieldName` field by mutable reference.
    fn get_field_mut_(&mut self)->&mut Self::Ty;

    /// Gets a mutable reference to the field.
    /// 
    /// # Safety
    /// 
    /// For the `ptr` argument,you must pass the return value of the
    /// `as_mutref` method for this field.
    /// 
    /// For the `getter` argument,you must pass the return value of the
    /// `get_field_mutref_func` method for this field.
    ///
    /// The `getter` argument is necessary for boxed trait objects.
    unsafe fn get_field_mutref(
        ptr:MutRef<'_,()>,
        getter:GetFieldMutRefFn<FieldName,Self::Ty>,
    )->&mut Self::Ty
    where 
        Self:Sized;

    /// Gets a pointer to the struct that contains this field.
    /// 
    /// Implementors must return a pointer to the same type that 
    /// `GetFieldMut::get_field_mutref` casts the pointer to.
    fn as_mutref(&mut self)->MutRef<'_,()>;

    /// Gets the `get_field_mutref` associated function as a function pointer.
    fn get_field_mutref_func(&self)->GetFieldMutRefFn<FieldName,Self::Ty>;
}


/////////////////////////////////////////////////

#[repr(transparent)]
pub struct GetFieldMutRefFn<FieldName,FieldTy>{
    pub func:unsafe fn(MutRef<'_,()>,Self)->&mut FieldTy,
    marker:PhantomData<FieldName>,
}

impl<FieldName,FieldTy> GetFieldMutRefFn<FieldName,FieldTy>{
    pub fn new(func:unsafe fn(MutRef<'_,()>,Self)->&mut FieldTy)->Self{
        Self{
            func,
            marker:PhantomData,
        }
    }
}

impl<FieldName,FieldTy> Copy for GetFieldMutRefFn<FieldName,FieldTy>{}

impl<FieldName,FieldTy> Clone for GetFieldMutRefFn<FieldName,FieldTy>{
    #[inline(always)]
    fn clone(&self)->Self{
        *self
    }
}

/////////////////////////////////////////////////


/// Converts this type into its `FieldName` field.
///
/// # Usage as Bound Example
///
/// This example demonstrates how you can use this trait as a bound.
///
/// If you have a lot of field accessor bounds you could use `structural_alias` macro
/// to alias those bounds and use that alias instead.
///
/// ```rust
/// use structural::{IntoField,GetFieldExt,GetFieldType,TI,ti};
/// 
/// fn into_value<T,V>(this:T)->V
/// where
///     T:IntoField<TI!(v a l u e), Ty=V>,
/// {
///     this.into_field(ti!(value))
/// }
///
/// #[derive(structural::Structural)]
/// struct Huh<T>{
///     #[struc(access="move")]
///     value:T,
/// }
/// 
/// fn main(){
///     let this=Huh{value:"Hello, World!"};
///     assert_eq!(into_value(this),"Hello, World!");
/// }
/// 
/// ```
///
/// # Manual Implementation Example
///
/// While this trait is intended to be implemented using the `Structural` derive macro,
/// you can manually implement it like this:
///
/// ```rust
/// use structural::{
///     GetField,IntoField,Structural,TI,TList,
///     structural_trait::{FieldInfo,TField},
///     mut_ref::MutRef,
///     impl_structural_dyn,
/// };
///
/// struct Huh<T>{
///     value:T,
/// }
///
///
/// impl<T> Structural for Huh<T>{
///     const FIELDS:&'static[FieldInfo]=&[FieldInfo::not_renamed("value")];
///
///     type Fields=TList![ TField<TI!(v a l u e),T> ];
/// }
///
/// impl_structural_dyn!{ impl[T] Huh<T> }
///
/// impl<T> GetField<TI!(v a l u e)> for Huh<T>{
///     type Ty=T;
///
///     fn get_field_(&self)->&Self::Ty{
///         &self.value
///     }
/// }
///
/// impl<T> IntoField<TI!(v a l u e)> for Huh<T>{
///     fn into_field_(self)->Self::Ty{
///         self.value
///     }
///
///     structural::impl_box_into_field_method!{TI!(v a l u e)}
/// }
///
/// ```
///
pub trait IntoField<FieldName>:GetField<FieldName>{
    /// Converts self into the field.
    fn into_field_(self)->Self::Ty
    where Self:Sized;

    /// Converts a boxed self into the field.
    #[cfg(feature="alloc")]
    fn box_into_field_(self: crate::alloc::boxed::Box<Self>)->Self::Ty;
}


/// An alias for a shared,mutable,and by-value accessor for a field.
pub trait IntoFieldMut<FieldName>:IntoField<FieldName>+GetFieldMut<FieldName>{}

impl<This,FieldName> IntoFieldMut<FieldName> for This
where
    This:IntoField<FieldName>+GetFieldMut<FieldName>
{}



/// An extension trait,which defines methods for accessing fields generically.
pub trait GetFieldExt{
    /// Gets a reference to the ´FieldName´ field.
    ///
    /// This is named `field_` instead of `field`
    /// because `field` collides with the `DebugTuple`/`DebugStruct` method
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let tup=(1,1,2,3,5,8);
    ///
    /// assert_eq!( tup.field_(ti!(0)), &1 );
    /// assert_eq!( tup.field_(ti!(1)), &1 );
    /// assert_eq!( tup.field_(ti!(2)), &2 );
    /// assert_eq!( tup.field_(ti!(3)), &3 );
    /// assert_eq!( tup.field_(ti!(4)), &5 );
    /// assert_eq!( tup.field_(ti!(5)), &8 );
    ///
    /// ```
    #[inline(always)]
    fn field_<FieldName>(&self,_:FieldName)->&Self::Ty
    where 
        Self:GetField<FieldName>
    {
        self.get_field_()
    }

    /// Gets multiple references to fields.
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let tup=(1,1,2,3,5,8);
    ///
    /// assert_eq!( tup.fields(ti!(0,1)),  (&1,&1) );
    /// assert_eq!( tup.fields(ti!(3,2)),  (&3,&2) );
    /// assert_eq!( tup.fields(ti!(4,5,3)),(&5,&8,&3) );
    ///
    /// ```
    #[inline(always)]
    fn fields<'a,Fields>(&'a self,_:TStringSet<Fields>)->Fields::MultiTy
    where
        Fields:GetMultiField<'a,Self>
    {
        Fields::multi_get_field_(self)
    }

    /// Gets a mutable reference to the ´FieldName´ field.
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let mut tup=(1,1,2,3,5,8);
    ///
    /// assert_eq!( tup.field_mut(ti!(0)), &mut 1 );
    /// assert_eq!( tup.field_mut(ti!(1)), &mut 1 );
    /// assert_eq!( tup.field_mut(ti!(2)), &mut 2 );
    /// assert_eq!( tup.field_mut(ti!(3)), &mut 3 );
    /// assert_eq!( tup.field_mut(ti!(4)), &mut 5 );
    /// assert_eq!( tup.field_mut(ti!(5)), &mut 8 );
    ///
    /// ```
    #[inline(always)]
    fn field_mut<FieldName>(&mut self,_:FieldName)->&mut Self::Ty
    where 
        Self:GetFieldMut<FieldName>
    {
        self.get_field_mut_()
    }

    /// Gets multiple mutable references to fields.
    ///
    /// This is safe since `TStringSet` requires its strings 
    /// to be checked for uniqueness before being constructed
    /// (the safety invariant of `TStringSet`).
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let mut tup=(1,1,2,3,5,8);
    ///
    /// assert_eq!( tup.fields_mut(ti!(0,1)), (&mut 1,&mut 1) );
    /// assert_eq!( tup.fields_mut(ti!(3,2)), (&mut 3,&mut 2) );
    /// assert_eq!( tup.fields_mut(ti!(4,5,3)), (&mut 5,&mut 8,&mut 3) );
    ///
    /// ```
    #[inline(always)]
    fn fields_mut<'a,Fields>(&'a mut self,ms:TStringSet<Fields>)->Fields::MultiTy
    where
        Fields:GetMultiFieldMut<'a,Self>,
        Self:Sized,
    {
        Fields::multi_get_field_mut_(self,ms)
    }

    /// Converts ´self´ into the ´FieldName´ field.
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let tup=(1,1,2,3,5,8);
    ///
    /// assert_eq!( tup.clone().into_field(ti!(0)), 1 );
    /// assert_eq!( tup.clone().into_field(ti!(1)), 1 );
    /// assert_eq!( tup.clone().into_field(ti!(2)), 2 );
    /// assert_eq!( tup.clone().into_field(ti!(3)), 3 );
    /// assert_eq!( tup.clone().into_field(ti!(4)), 5 );
    /// assert_eq!( tup.clone().into_field(ti!(5)), 8 );
    ///
    /// ```
    #[inline(always)]
    fn into_field<FieldName>(self,_:FieldName)->Self::Ty
    where 
        Self:IntoField<FieldName>+Sized,
    {
        self.into_field_()
    }

    /// Converts a boxed ´self´ into the ´FieldName´ field.
    ///
    /// # Example
    ///
    /// ```
    /// use structural::{GetFieldExt,ti};
    ///
    /// let tup=Box::new((1,1,2,3,5,8));
    ///
    /// assert_eq!( tup.clone().box_into_field(ti!(0)), 1 );
    /// assert_eq!( tup.clone().box_into_field(ti!(1)), 1 );
    /// assert_eq!( tup.clone().box_into_field(ti!(2)), 2 );
    /// assert_eq!( tup.clone().box_into_field(ti!(3)), 3 );
    /// assert_eq!( tup.clone().box_into_field(ti!(4)), 5 );
    /// assert_eq!( tup.clone().box_into_field(ti!(5)), 8 );
    ///
    /// ```
    #[cfg(feature="alloc")]
    #[inline(always)]
    fn box_into_field<FieldName>(self:crate::alloc::boxed::Box<Self>,_:FieldName)->Self::Ty
    where 
        Self:IntoField<FieldName>,
    {
        self.box_into_field_()
    }
}


impl<T:?Sized> GetFieldExt for T{}



///////////////////////////////////////////////////////////////////////////////


#[cfg(feature="alloc")]
macro_rules! unsized_impls {
    ( shared,$ptr:ident ) => {

        impl<T> Structural for $ptr<T>
        where
            T:Structural
        {
            const FIELDS:&'static [FieldInfo]=T::FIELDS;

            type Fields=T::Fields;
        }

        impl<T> StructuralDyn for $ptr<T>
        where
            T:StructuralDyn+?Sized
        {
            fn fields_info(&self)->&'static[FieldInfo]{
                (**self).fields_info()
            }
        }


        impl<This,Name,Ty> GetField<Name> for $ptr<This>
        where
            This:GetField<Name,Ty=Ty>+?Sized
        {
            type Ty=Ty;

            fn get_field_(&self)->&Self::Ty{
                (**self).get_field_()
            }
        }
    };
    (mutable,$ptr:ident)=>{

        unsized_impls!{ shared,$ptr }

        unsafe impl<T,FieldName,Ty> GetFieldMut<FieldName> for Box<T>
        where
            T:GetFieldMut<FieldName,Ty=Ty>+?Sized
        {
            /// Accesses the `FieldName` field by mutable reference.
            fn get_field_mut_(&mut self)->&mut Self::Ty{
                (**self).get_field_mut_()
            }

            default_if!{
                cfg(feature="specialization")
                unsafe fn get_field_mutref(
                    ptr:MutRef<'_,()>,
                    get_field:GetFieldMutRefFn<FieldName,Self::Ty>
                )->&mut Self::Ty{
                    (get_field.func)(ptr,get_field)
                }
            }

            fn as_mutref(&mut self)->MutRef<'_,()>{
                (**self).as_mutref()
            }

            fn get_field_mutref_func(&self)->GetFieldMutRefFn<FieldName,Ty>{
                (**self).get_field_mutref_func()
            }
        }


        #[cfg(feature="specialization")]
        unsafe impl<T,FieldName,Ty> GetFieldMut<FieldName> for Box<T>
        where
            T:GetFieldMut<FieldName,Ty=Ty>
        {
            unsafe fn get_field_mutref(
                ptr:MutRef<'_,()>,
                get_field:GetFieldMutRefFn<FieldName,Self::Ty>
            )->&mut Self::Ty{
                T::get_field_mutref(ptr,get_field)
            }
        }
    };
    (value,$ptr:ident)=>{
        
        unsized_impls!{ mutable,$ptr }

    };
}

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

    use crate::{
        alloc::{
            boxed::Box,
            rc::Rc,
            sync::Arc,
        },
        structural_trait::FieldInfo,
    };

    unsized_impls!{value,Box}
    unsized_impls!{shared,Arc}
    unsized_impls!{shared,Rc}
}