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;
use crate progmem;
use crate 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
//
// We use Derivative here to get rid of the constraint on the impls, which
// a normal derive would add.
// 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.
/// Implement `uDebug` by hand, because the derive variant adds a sized constraint.
///
unsafe
unsafe
/// Utilities to work with an array in progmem.
/// Loading elements of an array in progmem.
/// Utilities to work with an slice wrapper.
///
/// You can obtain a slice wrapper by coercing an array wrapper.
/// Loading elements of an array in progmem.
/// 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;
/// ```
/// An iterator over an array in progmem.
///
/// Can be acquired via [`ProgMem::iter`].
/// Same as [`ProgMem::iter`]
/// An iterator over an array in progmem, without loading elements
///
/// Can be acquired via [`ProgMem::wrapper_iter`].
/// 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);
/// ```
///
};
// Catch references rule, reference are evil!
// (well actually they are not, but most likely using them *is* a mistake)
=> ;
// Standard rule
=> ;
// Empty rule
=>
}
pub const
/// Only for internal use. Use the `progmem!` macro instead.
=> > = ;
};
// The rule creating an auto-sized progmem static via `ProgMem`
=> ;
// The normal rule creating a progmem static via `ProgMem`
=> ;
}
/// ```compile_fail
/// use avr_progmem::progmem;
/// progmem! {
/// static progmem AREF: &str = "Sometext";
/// }
/// ```
;
/// ```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();
/// }
/// ```
;