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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
//! Best-effort safe wrapper for progmem.
//!
//! This module offers the [`ProgMem`] struct that wraps pointers into progmem,
//! and only gives access to that value via methods that first load the value
//! into the normal data memory domain.
//! This is also the reason why the value must be `Copy` and is always returned
//! by-value instead of by-reference (since the value is not in the data memory
//! where it could be referenced).
//!
//! Since the `ProgMem` struct loads the value using special instructions,
//! it really must be in progmem, otherwise it would be **undefined behavior**
//! to use any of its methods.
//! Therefore, its constructor is `unsafe` where the
//! caller must guarantee that the given pointer truly points to a valid value
//! stored in progmem.
//!
//! As convenience, the [`progmem`] macro is offered that will create
//! a `static` in progmem with the given value and wrap a pointer to it in the
//! [`ProgMem`] struct for you.


use derivative::Derivative;

#[cfg(doc)]
use crate::progmem;
use crate::raw::read_value;



/// Best-effort safe wrapper around a value in program memory.
///
/// This type wraps a pointer to a value that is stored in program memory,
/// and offers safe functions to [`load`](ProgMem::load) that value from
/// program memory into the data memory domain from where it can be normally
/// used.
///
/// Since its constructor is the single most critical point in its API,
/// it is `unsafe`, despite it is supposed to be a safe wrapper (hence the
/// 'best-effort' notation).
/// The caller of the constructor therefore must ensure that the supplied
/// pointer points to a valid value stored in program memory.
///
/// Consequently, the only way to use this struct soundly is to define a
/// `static` with the `#[link_section = ".progmem.data"]` attribute on it and
/// pass a pointer to that `static` to `ProgMem::new`.
/// However, having an accessible `static` around that is stored in progmem
/// is a very dangerous endeavor.
///
/// In order to make working with progmem safer and more convenient,
/// consider using the [`progmem`] macro, that will put the given data
/// into a hidden `static` in progmem and provide you with an accessible static
/// containing the pointer to it wrapped in `ProgMem`.
///
/// Since this is just a fancy immutable pointer type, it can always be
/// copied/cloned (just copies the address). It also implements `Debug`,
/// which simply prints the address (into progmem) of the wrapped value.
/// And you can even coerce the pointed-to type e.g. from an statically sized
/// array to a dynamically sized slice type (it also allow to coerce to a trait
/// object, but those will not be useful at all), either using the
/// [`as_slice`][ProgMem::as_slice] method, or by enabling the "unsize" crate
/// feature that allows normal Rust coercing.
///
///
/// # Safety
///
/// The `target` pointer in this struct must point to a valid object of type
/// `T` that is stored in the program memory domain.
/// The object must be initialized, readable, and immutable (i.e. it must not
/// be changed).
/// Also the `target` pointer must be valid for the `'static` lifetime.
///
/// However, the requirement about the program memory domain only applies
/// to the AVR architecture (`#[cfg(target_arch = "avr")]`),
/// otherwise normal data access primitives are used.
/// This means that the value must be stored in the
/// regular data memory domain for ALL OTHER architectures! This still
/// holds, even if such other architecture is of the Harvard architecture,
/// because this is an AVR-only crate, not a general Harvard architecture
/// crate!
///
//
//
// SAFETY: Must not be publicly creatable
#[non_exhaustive]
//
// We use Derivative here to get rid of the constraint on the impls, which
// a normal derive would add.
#[derive(Derivative)]
// This is just a pointer type/wrapper thus it is safe & sound to just copy it.
// Notice, it will just copy the pointer (i.e. the address), thus `T` doesn't
// even need to implement any of these traits.
#[derivative(Copy(bound = ""), Clone(bound = ""), Debug(bound = ""))]
pub struct ProgMem<T: ?Sized> {
	/// Points to some `T` in progmem.
	///
	/// # Safety
	///
	/// See the struct doc.
	target: *const T,
}


/// Implement `uDebug` by hand, because the derive variant adds a sized constraint.
///
#[cfg(feature = "ufmt")]
impl<T: ?Sized> ufmt::uDebug for ProgMem<T> {
	fn fmt<W>(&self, fmt: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
	where
		W: ufmt::uWrite + ?Sized,
	{
		fmt.debug_struct("ProgMem")?
			// It be better to just pass the pointer as is,
			// however `ufmt` has - for what ever reason - a size constraint,
			// so we first cast it down to a sized type.
			.field("target", &self.target.cast::<()>())?
			.finish()
	}
}

unsafe impl<T: ?Sized> Send for ProgMem<T> {
	// SAFETY: pointers per-se are sound to send & share.
	// Further more, we will never mutate the underling value, thus `ProgMem`
	// can be considered as some sort of sharable `'static` "reference".
	// Thus it can be shared and transferred between threads.
}

unsafe impl<T: ?Sized> Sync for ProgMem<T> {
	// SAFETY: pointers per-se are sound to send & share.
	// Further more, we will never mutate the underling value, thus `ProgMem`
	// can be considered as some sort of sharable `'static` "reference".
	// Thus it can be shared and transferred between threads.
}

impl<T: ?Sized> ProgMem<T> {
	/// Return the raw pointer to the inner value.
	///
	/// Notice that the returned pointer is indeed a pointer into the progmem
	/// domain! It may **never** be dereferenced via the default Rust operations.
	/// That means a `unsafe{*pm.as_ptr()}` is **undefined behavior**!
	///
	/// Instead, if you want to use the pointer, you may want to use one of
	/// the "raw" functions, see the [raw](crate::raw) module.
	///
	pub fn as_ptr(&self) -> *const T {
		self.target
	}
}

impl<T> ProgMem<T> {
	/// Construct a new instance of this type.
	///
	/// This struct is a pointer wrapper for data in the program memory domain.
	/// Therefore when constructing this struct, it must be guaranteed
	/// that the pointed data is stored in progmem!
	/// This contract is expressed by the fact that this function is `unsafe`.
	/// See the Safety section for details.
	///
	/// You should not need to call this function directly.
	/// It is recommended to use the [`progmem`] macro instead (which calls
	/// this constructor for you, while enforcing its contract.
	///
	///
	/// # Safety
	///
	/// The `ProgMem` wrapper is build around the invariant that the wrapped
	/// pointer is stored in the program code memory domain (on the AVR
	/// architecture).
	///
	/// That means that this function is only sound to call, if the value to
	/// which `target` points is stored in a `static` that is stored in progmem,
	/// e.g. by using the attribute `#[link_section = ".progmem.data"]`.
	///
	/// However, the above requirement about the program memory domain only
	/// applies to the AVR architecture (`#[cfg(target_arch = "avr")]`),
	/// otherwise normal data access primitives are used,
	/// and thus the `target` pointer needs to point to normal data on those
	/// architectures.
	///
	pub const unsafe fn new(target: *const T) -> Self {
		ProgMem {
			target,
		}
	}
}

impl<T: Copy> ProgMem<T> {
	/// Read the inner value from progmem and return a regular value.
	///
	/// # Panics
	///
	/// This method panics, if the size of the value (i.e. `size_of::<T>()`)
	/// is beyond 255 bytes.
	/// However, this is currently just a implementation limitation, which may
	/// be lifted in the future.
	///
	/// Also notice, if you really hit this limit, you would need 256+ bytes on
	/// your stack, on the Arduino Uno (at least) that means that you might be
	/// close to a stack overflow. Thus it might be better to restructure your
	/// data, so you can store it as an array of something, than you can use
	/// the [`load_at`] and [`load_sub_array`] methods instead.
	///
	/// [`load_at`]: struct.ProgMem.html#method.load_at
	/// [`load_sub_array`]: struct.ProgMem.html#method.load_sub_array
	///
	pub fn load(&self) -> T {
		// This is safe, because the invariant of this struct guarantees that
		// this value (i.e. target) is stored in the progmem domain,
		// which is what `read_value` requires from us.
		unsafe { read_value(self.target) }
	}
}

/// Utilities to work with an array in progmem.
impl<T, const N: usize> ProgMem<[T; N]> {
	/// Get a reference to an element from the array, without loading it.
	///
	/// # Panics
	///
	/// This method panics, if the given index `idx` is grater or equal to the
	/// length `N` of the array.
	pub fn at(&self, idx: usize) -> ProgMem<T> {
		// Just use the slice impl
		let slice: ProgMem<[T]> = self.as_slice();
		slice.at(idx)
	}

	/// Iterate over all elements as wrappers.
	///
	/// Returns an iterator, which yields each element as a `ProgMem<T>`,
	/// which can be subsequently loaded.
	pub fn wrapper_iter(&self) -> PmWrapperIter<T> {
		PmWrapperIter::new(self.as_slice())
	}

	/// Returns the length of the array (i.e. `N`)
	pub fn len(&self) -> usize {
		N
	}

	/// Coerce this array wrapper into a slice wrapper.
	///
	/// Notice, if you enable the "unsize" crate feature, you can directly
	/// coerce the `ProgMem` struct, otherwise you have to use this function
	/// instead.
	///
	/// This analog to normal Rust coercing of arrays to slices.
	/// Indeed, if you enable the crate feature "unsize", you can use normal
	/// Rust coercing to get the same result.
	///
	/// # Examples
	///
	/// ```rust
	/// use avr_progmem::wrapper::ProgMem;
	/// use avr_progmem::progmem;
	///
	/// progmem!{
	///	    static progmem ARR: [u8; 3] = [1,2,3];
	/// }
	///
	/// // The array wrapper
	/// let arr: ProgMem<[u8; 3]> = ARR;
	/// // Coerced to a slice wrapper.
	/// let s: ProgMem<[u8]> = arr.as_slice();
	///
	/// // If you enable the "unsize" crate feature, you can just coerce like that:
	/// #[cfg(feature = "unsize")]
	/// let s: ProgMem<[u8]> = arr;
	/// ```
	///
	pub fn as_slice(&self) -> ProgMem<[T]> {
		ProgMem {
			target: self.target,
		}
	}
}

/// Loading elements of an array in progmem.
impl<T: Copy, const N: usize> ProgMem<[T; N]> {
	/// Load a single element from the inner array.
	///
	/// This method is analog to a slice indexing `self.load()[idx]`, so the
	/// same requirements apply, like the index `idx` should be less then the
	/// length `N` of the array, otherwise a panic will be risen.
	///
	///
	/// # Panics
	///
	/// This method panics, if the given index `idx` is grater or equal to the
	/// length `N` of the inner type.
	///
	/// This method also panics, if the size of the value (i.e. `size_of::<T>()`)
	/// is beyond 255 bytes.
	/// However, this is currently just a implementation limitation, which may
	/// be lifted in the future.
	///
	/// Notice, that here `T` is the type of the elements not the entire array
	/// as it would be with [`load`](Self::load).
	///
	pub fn load_at(&self, idx: usize) -> T {
		// Just get the element wrapper and load it
		self.at(idx).load()
	}

	/// Loads a sub array from the inner array.
	///
	/// This method is analog to a sub-slicing `self.load()[idx..(idx+M)]` but
	/// returning an owned array instead of a slice, simply because it has to
	/// copy the data anyway from the progmem into the data domain (i.e. the
	/// stack).
	///
	/// Also notice, that since this crate is intended for AVR
	/// micro-controllers, static arrays are generally preferred over
	/// dynamically allocated types such as a `Vec`.
	///
	///
	/// # Panics
	///
	/// This method panics, if the given index `idx` is grater or equal to the
	/// length `N` of the inner array, or the end index `idx+M` is grater than
	/// the length `N` of the inner array.
	///
	/// This method also panics, if the size of the value
	/// (i.e. `size_of::<[T;M]>()`) is beyond 255 bytes.
	/// However, this is currently just a implementation limitation, which may
	/// be lifted in the future.
	///
	pub fn load_sub_array<const M: usize>(&self, start_idx: usize) -> [T; M] {
		// Just a check to give a nicer panic message
		assert!(
			M <= N,
			"The sub array can not be grater than the source array"
		);

		// SAFETY: bounds check, the last element of the sub array must
		// still be within the source array (i.e. self)
		assert!(
			start_idx + M <= N,
			"The sub array goes beyond the end of the source array"
		);

		let first_source_element_ptr: *const T = self.target.cast();

		// Get a point to the selected element
		let first_output_element_ptr = first_source_element_ptr.wrapping_add(start_idx);

		// Pointer into as sub array into the source
		let sub_array_ptr: *const [T; M] = first_output_element_ptr.cast();

		// SAFETY: This is safe, because the invariant of this struct demands
		// that this value (i.e. self and thus also its inner value) are stored
		// in the progmem domain, which is what `read_value` requires from us.
		unsafe { read_value(sub_array_ptr) }
	}

	/// Lazily iterate over all elements
	///
	/// Returns an iterator which lazily loads the elements one at a time
	/// from progmem.
	/// This means this iterator can be used to access huge arrays while
	/// only requiring `size_of::<T>()` amount of stack memory.
	///
	/// # Panics
	///
	/// The returned iterator will panic, if the size of an element (i.e. `size_of::<T>()`)
	/// is beyond 255 bytes.
	/// However, this is currently just a implementation limitation, which may
	/// be lifted in the future.
	///
	/// Notice, that here `T` is the type of the elements not the entire array
	/// as it would be with [`load`](Self::load).
	///
	pub fn iter(&self) -> PmIter<T, N> {
		PmIter::new(self)
	}
}

/// Utilities to work with an slice wrapper.
///
/// You can obtain a slice wrapper by coercing an array wrapper.
impl<T> ProgMem<[T]> {
	/// Get a reference to an element from the array, without loading it.
	///
	/// # Panics
	///
	/// This method panics, if the given index `idx` is grater or equal to the
	/// length of the slice.
	pub fn at(&self, idx: usize) -> ProgMem<T> {
		// SAFETY: check that `idx` is in bounds
		assert!(idx < self.target.len(), "Given index is out of bounds");

		let first_element_ptr: *const T = self.target.cast();

		// Get a point to the selected element
		let element_ptr = first_element_ptr.wrapping_add(idx);

		// This sound, because `self.target` is in program domain and we checked
		// above that `idx` is in bound, thus that element pointer is also
		// valid and pointing into the program domain.
		ProgMem {
			target: element_ptr,
		}
	}

	/// Iterate over all elements as wrappers.
	///
	/// Returns an iterator, which yields each element as a `ProgMem<T>`,
	/// which can be subsequently loaded.
	pub fn wrapper_iter(&self) -> PmWrapperIter<T> {
		PmWrapperIter::new(*self)
	}

	/// Returns the length of the slice
	pub fn len(&self) -> usize {
		self.target.len()
	}
}

/// Loading elements of an array in progmem.
impl<T: Copy> ProgMem<[T]> {
	/// Load a single element from the slice.
	///
	/// This method is analog to a slice indexing, thus the same requirements
	/// apply: the index `idx` should be less then the length of the slice,
	/// otherwise a panic will be risen.
	///
	///
	/// # Panics
	///
	/// This method panics, if the given index `idx` is grater or equal to the
	/// length of the slice.
	///
	/// This method also panics, if the size of the value (i.e. `size_of::<T>()`)
	/// is beyond 255 bytes.
	/// However, this is currently just a implementation limitation, which may
	/// be lifted in the future.
	///
	/// Notice, that here `T` is the type of the elements not the entire slice.
	///
	pub fn load_at(&self, idx: usize) -> T {
		// Just get the element wrapper and load it
		self.at(idx).load()
	}
}


/// Allows coercing a `ProgMem<T>` to a `ProgMem<U>`, where U might be unsized.
///
/// A classic example of this is coercing an array `ProgMem<[T; N]>` into a
/// slice `ProgMem<[T]>`. Thus this impl is a generalization of the
/// [`as_slice`][ProgMem::as_slice] method.
///
/// # Examples
///
/// ```rust
/// use avr_progmem::wrapper::ProgMem;
/// use avr_progmem::progmem;
///
/// progmem!{
///	    static progmem ARR: [u8; 3] = [1,2,3];
/// }
///
/// // The array wrapper
/// let arr: ProgMem<[u8; 3]> = ARR;
/// // Coerced to a slice wrapper, just like that.
/// let s: ProgMem<[u8]> = arr;
/// ```
#[cfg(feature = "unsize")]
impl<T: ?Sized, U: ?Sized> core::ops::CoerceUnsized<ProgMem<U>> for ProgMem<T> where
	T: core::marker::Unsize<U>
{
}

/// An iterator over an array in progmem.
///
/// Can be acquired via [`ProgMem::iter`].
pub struct PmIter<'a, T, const N: usize> {
	progmem: &'a ProgMem<[T; N]>,
	current_idx: usize,
}

impl<'a, T, const N: usize> PmIter<'a, T, N> {
	/// Creates a new iterator over the given progmem array.
	pub const fn new(pm: &'a ProgMem<[T; N]>) -> Self {
		Self {
			progmem: pm,
			current_idx: 0,
		}
	}
}

impl<'a, T: Copy, const N: usize> Iterator for PmIter<'a, T, N> {
	type Item = T;

	fn next(&mut self) -> Option<Self::Item> {
		// Check for iterator end
		if self.current_idx < N {
			// Load next item from progmem
			let b = self.progmem.load_at(self.current_idx);
			self.current_idx += 1;

			Some(b)
		} else {
			None
		}
	}
}

/// Same as [`ProgMem::iter`]
impl<'a, T: Copy, const N: usize> IntoIterator for &'a ProgMem<[T; N]> {
	type IntoIter = PmIter<'a, T, N>;
	type Item = T;

	fn into_iter(self) -> Self::IntoIter {
		self.iter()
	}
}

/// An iterator over an array in progmem, without loading elements
///
/// Can be acquired via [`ProgMem::wrapper_iter`].
pub struct PmWrapperIter<T> {
	progmem: ProgMem<[T]>,
	current_idx: usize,
}

impl<T> PmWrapperIter<T> {
	/// Creates a new iterator over the given progmem array.
	pub const fn new(pm: ProgMem<[T]>) -> Self {
		Self {
			progmem: pm,
			current_idx: 0,
		}
	}
}

impl<T> Iterator for PmWrapperIter<T> {
	type Item = ProgMem<T>;

	fn next(&mut self) -> Option<Self::Item> {
		// Check for iterator end
		if self.current_idx < self.progmem.len() {
			// Get next element wrapper
			let b = self.progmem.at(self.current_idx);
			self.current_idx += 1;

			Some(b)
		} else {
			None
		}
	}
}



/// Define a static in progmem.
///
/// This is a helper macro to simplify the definition of statics that are valid
/// to be wrapped in the `ProgMem` struct thus providing a safe way to work
/// with data in progmem.
///
/// Thus this macro essentially takes a user static definition and emits a
/// definition that is defined to be stored in the progmem section and then is
/// wrap in the `ProgMem` wrapper for safe access.
///
/// There are essentially three types of statics that you can created:
///
/// * ordinary fixed-size data, e.g. a `u8`, `(u16,u32)`, or your own struct.
/// * "auto-sized" arrays, essentially any kind of array `[T; N]`
/// * strings, i.e. anything `str`-ish such as string literals
///
///
/// # Ordinary Data
///
/// You can store any `Copy + Sized` data in progmem and load it at your
/// leisure.
///
/// ## Example
///
/// ```
/// use avr_progmem::progmem;
///
/// #[derive(Copy, Clone)]
/// struct Foo {
///     a: u16,
///     b: u32,
/// }
///
/// progmem!{
///     /// Static data stored in progmem!
///     pub static progmem BYTE: u8 = b'a';
///
///     /// Anything that is `Copy + Sized`
///     pub static progmem FOO: Foo = Foo { a: 42, b: 42 * 42 };
/// }
///
/// // Loading the byte from progmem onto the stack
/// let data: u8 = BYTE.load();
/// assert_eq!(b'a', data);
///
/// // Loading the arbitrary data
/// let foo: Foo = FOO.load();
/// assert_eq!(42, foo.a);
/// assert_eq!(1764, foo.b);
/// ```
///
///
/// # Arrays
///
/// Notice, that to access ordinary data from the progmem you have to load it
/// as whole before you can do anything with it.
/// In other words you can't just load `foo.a`, you have to first load the
/// entire struct into RAM.
///
/// When we have arrays, stuff can get hugh quickly, therefore,
/// specifically for arrays, we have additionally accessors to access elements
/// individually, without the burden to load the entire array first.
///
/// ```
/// use avr_progmem::progmem;
///
/// progmem!{
///     /// A simple array using ordinary syntax
///     pub static progmem ARRAY: [u16; 4] = [1, 2, 3, 4];
/// }
///
/// // We can still load the entire array (but you shouldn't do this with
/// // big arrays)
/// let array: [u16; 4] = ARRAY.load();
/// assert_eq!([1,2,3,4], array);
///
/// // We can also load individual elements
/// let last_elem: u16 = ARRAY.load_at(3);
/// assert_eq!(4, last_elem);
///
/// // And even arbitrary sub-arrays (tho they need to be statically sized)
/// let middle_stuff: [u16; 2] = ARRAY.load_sub_array(1);
/// assert_eq!([2, 3], middle_stuff);
///
/// // Finally, we can iterate the array lazily loading one byte after another
/// // so we need only just enough RAM for to handle a single element
/// let mut elem_iter = ARRAY.iter();
/// assert_eq!(Some(1), elem_iter.next());
/// assert_eq!(Some(2), elem_iter.next());
/// assert_eq!(Some(3), elem_iter.next());
/// assert_eq!(Some(4), elem_iter.next());
/// assert_eq!(None, elem_iter.next());
/// ```
///
/// ## Auto-Sizing
///
/// While we could use arrays with the syntax from above, we get also use an
/// alternative syntax, where the array size is gets inferred which is
/// particularly useful if you include external data (e.g. form a file).
///
/// ```
/// use avr_progmem::progmem;
///
/// progmem!{
///     /// An "auto-sized" array (the size is inferred and made accessible by
///     /// a constant named `DATA_LEN`, tho any name would do)
///     pub static progmem<const DATA_LEN: usize> DATA: [u8; DATA_LEN] =
///         *include_bytes!("../examples/test_text.txt"); // assume it's binary
/// }
///
/// // "auto-sized" array can be accessed in the exactly same way as ordinary
/// // arrays, we just don't need to hardcode the size, and even get this nice
/// // constant at our disposal.
/// let middle: u8 = DATA.load_at(DATA_LEN / 2);
/// assert_eq!(32, middle);
/// ```
///
/// # Strings
///
/// Strings are complicated, partially, because in Rust strings such as `str`
/// are unsized making storing them a nightmare (normally the compiler somehow
/// manages to automagically put all your string literals into static memory,
/// but you can't have a `static` that stores a `str` by-value, that is without
/// the `&`).
/// The next best thing that one can do to store a "string" is to store some
/// fix-size array either of `char`s or of UTF-8 encoded `u8`s, which aren't
/// exactly `str` and thus much more cumbersome to use.
/// Therefore, this crate has dedicated an entire
/// [module to strings](crate::string).
///
/// Consequently, this macro also has some special syntax to make string
/// literals, which are given as some `&str` and are automagically converted
/// into something more manageable
/// (i.e. a [`PmString`](crate::string::PmString)) and are put in this format
/// into a progmem `static`.
///
/// ## Examples
///
/// ```rust
/// use avr_progmem::progmem;
///
/// progmem! {
///     /// A static string stored in program memory as a `PmString`.
///     /// Notice the `string` keyword.
///     static progmem string TEXT = "Unicode text: 大賢者";
/// }
///
/// let text = TEXT.load();
/// assert_eq!("Unicode text: 大賢者", &*text);
/// ```
///
#[macro_export]
macro_rules! progmem {
	// Special string rule
	(
		$( #[ $attr:meta ] )*
		$vis:vis static progmem string $name:ident = $value:expr ;

		$($rest:tt)*
	) => {
		// Just forward to internal rule
		$crate::progmem_internal!{
			$(#[$attr])*
			$vis static progmem string $name = $value ;
		}

		// Recursive call to allow multiple items in macro invocation
		$crate::progmem!{
			$($rest)*
		}
	};

	// Catch "hand" strings rule, use the above special rule instead
	(
		$( #[ $attr:meta ] )*
		$vis:vis static progmem $name:ident : $( avr_progmem::string:: )? LoadedString < $ty:literal > = $( avr_progmem::string:: )?  LoadedString :: new ( $value:expr ) $( . unwrap () $(@ $unwrapped:ident)? )? ;

		$($rest:tt)*
	) => {
		// Make this a hard compile-time error.
		::core::compile_error!("Prefer using the special `PmString` rule with the `string` keyword.");
		::core::compile_error!(concat!("Use instead: ", stringify!($vis), " static progmem string ", stringify!($name), " = ..."));

		// Emit a dummy to suppress errors where `$name` is used
		static $name : $crate::wrapper::ProgMem< $crate::string::LoadedString< $ty > > = todo!();

		// Recursive call to allow multiple items in macro invocation
		$crate::progmem!{
			$($rest)*
		}
	};

	// Catch references rule, reference are evil!
	// (well actually they are not, but most likely using them *is* a mistake)
	(
		$( #[ $attr:meta ] )*
		$vis:vis static progmem $name:ident : & $ty:ty = $value:expr ;

		$($rest:tt)*
	) => {
		// Make this a hard compile-time error
		::core::compile_error!("Do not use a reference type for progmem, because this way only the reference itself would be in progmem, whereas the underlying data would still be in the normal data domain!");

		// Emit a dummy to suppress errors where `$name` is used
		static $name : & $ty = todo!();

		// Recursive call to allow multiple items in macro invocation
		$crate::progmem!{
			$($rest)*
		}
	};

	// Standard rule
	(
		$( #[ $attr:meta ] )*
		$vis:vis static progmem $( < const $size_name:ident : usize > )? $name:ident : $ty:ty = $value:expr ;

		$($rest:tt)*
	) => {
		// Crate the progmem static via internal macro
		$crate::progmem_internal!{
			$(#[$attr])* $vis static progmem $( < const $size_name : usize > )? $name : $ty = $value;
		}

		// Recursive call to allow multiple items in macro invocation
		$crate::progmem!{
			$($rest)*
		}
	};

	// Empty rule
	() => ()
}


#[doc(hidden)]
pub const fn array_from_str<const N: usize>(s: &str) -> [u8; N] {
	let array_ref = crate::string::from_slice::array_ref_try_from_slice(s.as_bytes());
	match array_ref {
		Ok(r) => *r,
		Err(_) => panic!("Invalid array size"),
	}
}


/// Only for internal use. Use the `progmem!` macro instead.
#[doc(hidden)]
#[macro_export]
macro_rules! progmem_internal {
	// The string rule creating the progmem string static via `PmString`
	{
		$( #[ $attr:meta ] )*
		$vis:vis static progmem string $name:ident = $value:expr ;
	} => {
		// User attributes
		$(#[$attr])*
		// The facade static definition, this only contains a pointer and thus
		// is NOT in progmem, which in turn makes it safe & sound to access this
		// facade.
		$vis static $name: $crate::string::PmString<{
			// This bit runs at compile-time
			let s: &str = $value;
			s.len()
		}> = {
			// This inner hidden static contains the actual real raw value.
			//
			// SAFETY: it must be stored in the progmem or text section!
			// The `link_section` lets us define that:
			#[cfg_attr(target_arch = "avr", link_section = ".progmem.data")]
			static VALUE: [u8; {
				// This bit runs at compile-time
				let s: &str = $value;
				s.len()
			}] = $crate::wrapper::array_from_str( $value );

			let pm = unsafe {
				// SAFETY: This call is sound because we ensure with the above
				// `link_section` attribute on `VALUE` that it is indeed
				// in the progmem section.
				$crate::wrapper::ProgMem::new(
					::core::ptr::addr_of!(VALUE)
				)
			};

			// Just return the PmString wrapper around the local static
			unsafe {
				// SAFETY: This call is sound, because we started out with a
				// `&str` thus the conent of `VALUE` must be valid UTF-8
				$crate::string::PmString::new(
					pm
				)
			}
		};
	};

	// The rule creating an auto-sized progmem static via `ProgMem`
	{
		$( #[ $attr:meta ] )*
		$vis:vis static progmem < const $size_name:ident : usize > $name:ident : $ty:ty = $value:expr ;
	} => {
		// Create a constant with the size of the value, which is retrieved
		// via `SizedOwned` on the value, assuming it is an array of sorts.
		//#[doc = concat!("Size of [", stringify!( $name ))]
		$vis const $size_name : usize = {
			// This bit is a bit hacky, we just hope that the type of `$value`
			// has some `len` method.
			$value.len()
		};

		// Just a normal prgomem static, `$ty` may use the above constant
		$crate::progmem_internal!{
			$( #[ $attr ] )*
			$vis static progmem $name : $ty = $value ;
		}
	};

	// The normal rule creating a progmem static via `ProgMem`
	{
		$( #[ $attr:meta ] )*
		$vis:vis static progmem $name:ident : $ty:ty = $value:expr ;
	} => {
		// User attributes
		$(#[$attr])*
		// The facade static definition, this only contains a pointer and thus
		// is NOT in progmem, which in turn makes it safe & sound to access this
		// facade.
		$vis static $name: $crate::wrapper::ProgMem<$ty> = {
			// This inner hidden static contains the actual real raw value.
			//
			// SAFETY: it must be stored in the progmem or text section!
			// The `link_section` lets us define that:
			#[cfg_attr(target_arch = "avr", link_section = ".progmem.data")]
			static VALUE: $ty = $value;

			unsafe {
				// SAFETY: This call is sound because we ensure with the above
				// `link_section` attribute on `VALUE` that it is indeed
				// in the progmem section.
				$crate::wrapper::ProgMem::new(
					::core::ptr::addr_of!(VALUE)
				)
			}
		};
	};
}


/// ```compile_fail
/// use avr_progmem::progmem;
/// progmem! {
/// 	static progmem AREF: &str = "Sometext";
/// }
/// ```
#[cfg(doctest)]
pub struct ProgMemReferenceTest;


/// ```compile_fail
/// use avr_progmem::progmem;
/// progmem! {
/// 	// Should notify that we should use the `progmem string` rule instead
/// 	static progmem HAND_STRING: LoadedString<34> =
/// 		LoadedString::new("hand crafted progmem loaded string").unwrap();
/// }
/// ```
#[cfg(doctest)]
pub struct HandStringTest;