-
Notifications
You must be signed in to change notification settings - Fork 14
/
map.rs
1810 lines (1627 loc) · 60.9 KB
/
map.rs
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A module for storing key-value pairs in flash with minimal erase cycles.
//!
//! When a key-value is stored, it overwrites the any old items with the same key.
//!
//! ## Basic API:
//!
//! ```rust
//! # use sequential_storage::map::{store_item, fetch_item};
//! # use sequential_storage::cache::NoCache;
//! # use mock_flash::MockFlashBase;
//! # use futures::executor::block_on;
//! # type Flash = MockFlashBase<10, 1, 4096>;
//! # mod mock_flash {
//! # include!("mock_flash.rs");
//! # }
//! # fn init_flash() -> Flash {
//! # Flash::new(mock_flash::WriteCountCheck::Twice, None, false)
//! # }
//!
//! # block_on(async {
//! // Initialize the flash. This can be internal or external
//! let mut flash = init_flash();
//! // These are the flash addresses in which the crate will operate.
//! // The crate will not read, write or erase outside of this range.
//! let flash_range = 0x1000..0x3000;
//! // We need to give the crate a buffer to work with.
//! // It must be big enough to serialize the biggest value of your storage type in,
//! // rounded up to to word alignment of the flash. Some kinds of internal flash may require
//! // this buffer to be aligned in RAM as well.
//! let mut data_buffer = [0; 128];
//!
//! // We can fetch an item from the flash. We're using `u8` as our key type and `u32` as our value type.
//! // Nothing is stored in it yet, so it will return None.
//!
//! assert_eq!(
//! fetch_item::<u8, u32, _>(
//! &mut flash,
//! flash_range.clone(),
//! &mut NoCache::new(),
//! &mut data_buffer,
//! &42,
//! ).await.unwrap(),
//! None
//! );
//!
//! // Now we store an item the flash with key 42.
//! // Again we make sure we pass the correct key and value types, u8 and u32.
//! // It is important to do this consistently.
//!
//! store_item(
//! &mut flash,
//! flash_range.clone(),
//! &mut NoCache::new(),
//! &mut data_buffer,
//! &42u8,
//! &104729u32,
//! ).await.unwrap();
//!
//! // When we ask for key 42, we not get back a Some with the correct value
//!
//! assert_eq!(
//! fetch_item::<u8, u32, _>(
//! &mut flash,
//! flash_range.clone(),
//! &mut NoCache::new(),
//! &mut data_buffer,
//! &42,
//! ).await.unwrap(),
//! Some(104729)
//! );
//! # });
//! ```
//!
//! ## Key and value traits
//!
//! In the previous example we saw we used one key and one value type.
//! It is ***crucial*** we use the same key type every time on the same range of flash.
//! This is because the internal items are serialized as `[key|value]`. A different key type
//! will have a different length and will make all data nonsense.
//!
//! However, if we have special knowledge about what we store for each key,
//! we are allowed to use different value types.
//!
//! For example, we can do the following:
//!
//! 1. Store a u32 with key 0
//! 2. Store a custom type 'Foo' with key 1
//! 3. Fetch a u32 with key 0
//! 4. Fetch a custom type 'Foo' with key 1
//!
//! It is up to the user to make sure this is done correctly.
//! If done incorrectly, the deserialize function of requested value type will see
//! data it doesn't expect. In the best case it'll return an error, in a bad case it'll
//! give bad invalid data and in the worst case the deserialization code panics.
//! It is worth mentioning that `fetch_all_items` also requires that all items have the same type.
//! So be careful.
//!
//! For your convenience there are premade implementations for the [Key] and [Value] traits.
//!
use core::mem::{size_of, MaybeUninit};
use cache::CacheImpl;
use embedded_storage_async::nor_flash::MultiwriteNorFlash;
use crate::item::{find_next_free_item_spot, Item, ItemHeader, ItemIter};
use self::{
cache::{KeyCacheImpl, PrivateKeyCacheImpl},
item::{ItemHeaderIter, ItemUnborrowed},
};
use super::*;
/// Iterator which iterates all non-erased & non-corrupted items in the map.
///
/// The iterator will return the (Key, Value) tuple when calling `next()`.
/// If the iterator ends, it will return `Ok(None)`.
///
/// The following is a simple example of how to use the iterator:
/// ```rust
/// // Create the iterator of map items
/// let mut iterator = fetch_all_item::<u8, _, _>(
/// &mut flash,
/// flash_range.clone(),
/// &mut cache,
/// &mut buffer
/// )
/// .await
/// .unwrap();
///
/// // Iterate through all items, suppose the Key and Value types are u8, u32
/// while let Ok(Some((key, value))) = iterator
/// .next::<u8, u32>(&mut buffer)
/// .await
/// {
/// // Do somethinmg with the item.
/// // Please note that for the same key there might be multiple items returned,
/// // the last one is the current active one.
/// }
/// ```
pub struct MapItemIter<'d, 'c, S: NorFlash, CI: CacheImpl> {
flash: &'d mut S,
flash_range: Range<u32>,
first_page: usize,
cache: &'c mut CI,
current_page_index: usize,
pub(crate) current_iter: ItemIter,
}
impl<'d, 'c, S: NorFlash, CI: CacheImpl> MapItemIter<'d, 'c, S, CI> {
/// Get the next item in the iterator. Be careful that the given `data_buffer` should large enough to contain the serialized key and value.
pub async fn next<'a, K: Key, V: Value<'a>>(
&mut self,
data_buffer: &'a mut [u8],
) -> Result<Option<(K, V)>, Error<S::Error>> {
// Find the next item
let item = loop {
if let Some((item, _address)) = self.current_iter.next(self.flash, data_buffer).await? {
// We've found the next item, quit the loop
break item;
}
// The current page is done, we need to find the next page
// Find next page which is not open, update `self.current_iter`
loop {
self.current_page_index =
next_page::<S>(self.flash_range.clone(), self.current_page_index);
// We've looped back to the first page, which means all pages are checked, there's nothing left so we return None
if self.current_page_index == self.first_page {
return Ok(None);
}
match get_page_state::<S>(
self.flash,
self.flash_range.clone(),
self.cache,
self.current_page_index,
)
.await
{
Ok(PageState::Closed) | Ok(PageState::PartialOpen) => {
self.current_iter = ItemIter::new(
calculate_page_address::<S>(
self.flash_range.clone(),
self.current_page_index,
) + S::WORD_SIZE as u32,
calculate_page_end_address::<S>(
self.flash_range.clone(),
self.current_page_index,
) - S::WORD_SIZE as u32,
);
break;
}
_ => continue,
}
}
};
let data_len = item.header.length as usize;
let (key, key_len) = K::deserialize_from(item.data())?;
Ok(Some((
key,
V::deserialize_from(&data_buffer[key_len..][..data_len - key_len])
.map_err(Error::SerializationError)?,
)))
}
}
/// Get an iterator that iterates over all non-erased & non-corrupted items in the map.
///
/// <div class="warning">
/// You should be very careful when using the map item iterator:
/// <ul>
/// <li>
/// Because map doesn't erase the items when you insert a new one with the same key,
/// so it's possible that the iterator returns items with the same key multiple times.
/// Generally the last returned one is the `active` one.
/// </li>
/// <li>
/// The iterator requires ALL items in the storage have the SAME type.
/// If you have different types of items in your map, the iterator might return incorrect data or error.
/// </li>
/// </ul>
/// </div>
///
/// The following is a simple example of how to use the iterator:
/// ```rust
/// // Create the iterator of map items
/// let mut iterator = fetch_all_item::<u8, _, _>(
/// &mut flash,
/// flash_range.clone(),
/// &mut cache,
/// &mut buffer
/// )
/// .await
/// .unwrap();
///
/// // Iterate through all items, suppose the Key and Value types are u8, u32
/// while let Ok(Some((key, value))) = iterator
/// .next::<u8, u32>(&mut buffer)
/// .await
/// {
/// // Do somethinmg with the item.
/// // Please note that for the same key there might be multiple items returned,
/// // the last one is the current active one.
/// }
/// ```
///
pub async fn fetch_all_items<'d, 'c, K: Key, S: NorFlash, CI: KeyCacheImpl<K>>(
flash: &'d mut S,
flash_range: Range<u32>,
cache: &'c mut CI,
data_buffer: &mut [u8],
) -> Result<MapItemIter<'d, 'c, S, CI>, Error<S::Error>> {
// Get the first page index.
// The first page used by the map is the next page of the `PartialOpen` page or the last `Closed` page
let first_page = run_with_auto_repair!(
function = {
match find_first_page(flash, flash_range.clone(), cache, 0, PageState::PartialOpen)
.await?
{
Some(last_used_page) => {
// The next page of the `PartialOpen` page is the first page
Ok(next_page::<S>(flash_range.clone(), last_used_page))
}
None => {
// In the event that all pages are still open or the last used page was just closed, we search for the first open page.
// If the page one before that is closed, then that's the last used page.
if let Some(first_open_page) =
find_first_page(flash, flash_range.clone(), cache, 0, PageState::Open)
.await?
{
let previous_page =
previous_page::<S>(flash_range.clone(), first_open_page);
if get_page_state(flash, flash_range.clone(), cache, previous_page)
.await?
.is_closed()
{
// The previous page is closed, so the first_open_page is what we want
Ok(first_open_page)
} else {
// The page before the open page is not closed, so it must be open.
// This means that all pages are open and that we don't have any items yet.
cache.unmark_dirty();
Ok(0)
}
} else {
// There are no open pages, so everything must be closed.
// Something is up and this should never happen.
// To recover, we will just erase all the flash.
Err(Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
})
}
}
}
},
repair = try_repair::<K, _>(flash, flash_range.clone(), cache, data_buffer).await?
)?;
Ok(MapItemIter {
flash,
flash_range: flash_range.clone(),
first_page,
cache,
current_page_index: first_page,
current_iter: ItemIter::new(
calculate_page_address::<S>(flash_range.clone(), first_page) + S::WORD_SIZE as u32,
calculate_page_end_address::<S>(flash_range.clone(), first_page) - S::WORD_SIZE as u32,
),
})
}
/// Get the last stored value from the flash that is associated with the given key.
/// If no value with the key is found, None is returned.
///
/// The data buffer must be long enough to hold the longest serialized data of your [Key] + [Value] types combined,
/// rounded up to flash word alignment.
///
/// <div class="warning">
///
/// *You are required to, on a given flash range, use the same [Key] type every time. You are allowed to use*
/// *multiple [Value] types. See the module-level docs for more information about this.*
///
/// Also watch out for using integers. This function will take any integer and it's easy to pass the wrong type.
///
/// </div>
pub async fn fetch_item<'d, K: Key, V: Value<'d>, S: NorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &'d mut [u8],
search_key: &K,
) -> Result<Option<V>, Error<S::Error>> {
let result = run_with_auto_repair!(
function = {
fetch_item_with_location(flash, flash_range.clone(), cache, data_buffer, search_key)
.await
},
repair = try_repair::<K, _>(flash, flash_range.clone(), cache, data_buffer).await?
);
let Some((item, _, item_key_len)) = result? else {
return Ok(None);
};
let data_len = item.header.length as usize;
let item_key_len = match item_key_len {
Some(item_key_len) => item_key_len,
None => K::get_len(&data_buffer[..data_len])?,
};
Ok(Some(
V::deserialize_from(&data_buffer[item_key_len..][..data_len - item_key_len])
.map_err(Error::SerializationError)?,
))
}
/// Fetch the item, but with the item unborrowed, the address of the item and the length of the key
#[allow(clippy::type_complexity)]
async fn fetch_item_with_location<'d, K: Key, S: NorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl PrivateKeyCacheImpl<K>,
data_buffer: &'d mut [u8],
search_key: &K,
) -> Result<Option<(ItemUnborrowed, u32, Option<usize>)>, Error<S::Error>> {
assert_eq!(flash_range.start % S::ERASE_SIZE as u32, 0);
assert_eq!(flash_range.end % S::ERASE_SIZE as u32, 0);
assert!(flash_range.end - flash_range.start >= S::ERASE_SIZE as u32 * 2);
assert!(S::ERASE_SIZE >= S::WORD_SIZE * 3);
assert!(S::WORD_SIZE <= MAX_WORD_SIZE);
if cache.is_dirty() {
cache.invalidate_cache_state();
}
'cache: {
if let Some(cached_location) = cache.key_location(search_key) {
let page_index = calculate_page_index::<S>(flash_range.clone(), cached_location);
let page_data_end_address =
calculate_page_end_address::<S>(flash_range.clone(), page_index)
- S::WORD_SIZE as u32;
let Some(header) =
ItemHeader::read_new(flash, cached_location, page_data_end_address).await?
else {
// The cache points to a non-existing item?
if cfg!(feature = "_test") {
panic!("Wrong cache value. Addr: {cached_location}");
}
cache.invalidate_cache_state();
break 'cache;
};
let item = header
.read_item(flash, data_buffer, cached_location, page_data_end_address)
.await?;
match item {
item::MaybeItem::Corrupted(_, _) | item::MaybeItem::Erased(_, _) => {
if cfg!(feature = "_test") {
panic!("Wrong cache value. Addr: {cached_location}");
}
// The cache points to a corrupted or erased item?
cache.invalidate_cache_state();
break 'cache;
}
item::MaybeItem::Present(item) => {
return Ok(Some((item.unborrow(), cached_location, None)));
}
}
}
}
// We need to find the page we were last using. This should be the only partial open page.
let mut last_used_page =
find_first_page(flash, flash_range.clone(), cache, 0, PageState::PartialOpen).await?;
if last_used_page.is_none() {
// In the event that all pages are still open or the last used page was just closed, we search for the first open page.
// If the page one before that is closed, then that's the last used page.
if let Some(first_open_page) =
find_first_page(flash, flash_range.clone(), cache, 0, PageState::Open).await?
{
let previous_page = previous_page::<S>(flash_range.clone(), first_open_page);
if get_page_state(flash, flash_range.clone(), cache, previous_page)
.await?
.is_closed()
{
last_used_page = Some(previous_page);
} else {
// The page before the open page is not closed, so it must be open.
// This means that all pages are open and that we don't have any items yet.
cache.unmark_dirty();
return Ok(None);
}
} else {
// There are no open pages, so everything must be closed.
// Something is up and this should never happen.
// To recover, we will just erase all the flash.
return Err(Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
});
}
}
// We must now find the most recent storage item with the key that was asked for.
// If we don't find it in the current page, then we check again in the previous page if that page is closed.
let mut current_page_to_check = last_used_page.unwrap();
let mut newest_found_item_data = None;
loop {
let page_data_start_address =
calculate_page_address::<S>(flash_range.clone(), current_page_to_check)
+ S::WORD_SIZE as u32;
let page_data_end_address =
calculate_page_end_address::<S>(flash_range.clone(), current_page_to_check)
- S::WORD_SIZE as u32;
let mut it = ItemIter::new(page_data_start_address, page_data_end_address);
while let Some((item, address)) = it.next(flash, data_buffer).await? {
let (found_key, found_key_len) = K::deserialize_from(item.data())?;
if found_key == *search_key {
newest_found_item_data = Some((address, found_key_len));
}
}
// We've found the item! We can stop searching
if let Some((newest_found_item_address, _)) = newest_found_item_data.as_ref() {
cache.notice_key_location(search_key, *newest_found_item_address, false);
break;
}
// We have not found the item. We've got to look in the previous page, but only if that page is closed and contains data.
let previous_page = previous_page::<S>(flash_range.clone(), current_page_to_check);
if get_page_state(flash, flash_range.clone(), cache, previous_page).await?
!= PageState::Closed
{
// We've looked through all the pages with data and couldn't find the item
cache.unmark_dirty();
return Ok(None);
}
current_page_to_check = previous_page;
}
cache.unmark_dirty();
// We now need to reread the item because we lost all its data other than its address
if let Some((newest_found_item_address, newest_found_item_key_len)) = newest_found_item_data {
let item = ItemHeader::read_new(flash, newest_found_item_address, u32::MAX)
.await?
.ok_or_else(|| {
// How come there's no item header here!? We just found it!
Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
}
})?
.read_item(flash, data_buffer, newest_found_item_address, u32::MAX)
.await?;
Ok(Some((
item.unwrap()?.unborrow(),
newest_found_item_address,
Some(newest_found_item_key_len),
)))
} else {
Ok(None)
}
}
/// Store a key-value pair into flash memory.
/// It will overwrite the last value that has the same key.
/// The flash needs to be at least 2 pages long.
///
/// The data buffer must be long enough to hold the longest serialized data of your [Key] + [Value] types combined,
/// rounded up to flash word alignment.
///
/// <div class="warning">
///
/// *You are required to, on a given flash range, use the same [Key] type every time. You are allowed to use*
/// *multiple [Value] types. See the module-level docs for more information about this.*
///
/// Also watch out for using integers. This function will take any integer and it's easy to pass the wrong type.
///
/// </div>
pub async fn store_item<'d, K: Key, V: Value<'d>, S: NorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &mut [u8],
key: &K,
item: &V,
) -> Result<(), Error<S::Error>> {
run_with_auto_repair!(
function =
store_item_inner(flash, flash_range.clone(), cache, data_buffer, key, item).await,
repair = try_repair::<K, _>(flash, flash_range.clone(), cache, data_buffer).await?
)
}
async fn store_item_inner<'d, K: Key, S: NorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &mut [u8],
key: &K,
item: &dyn Value<'d>,
) -> Result<(), Error<S::Error>> {
assert_eq!(flash_range.start % S::ERASE_SIZE as u32, 0);
assert_eq!(flash_range.end % S::ERASE_SIZE as u32, 0);
assert!(flash_range.end - flash_range.start >= S::ERASE_SIZE as u32 * 2);
assert!(S::ERASE_SIZE >= S::WORD_SIZE * 3);
assert!(S::WORD_SIZE <= MAX_WORD_SIZE);
if cache.is_dirty() {
cache.invalidate_cache_state();
}
let mut recursion_level = 0;
loop {
// Check if we're in an infinite recursion which happens when we don't have enough space to store the new data
if recursion_level == get_pages::<S>(flash_range.clone(), 0).count() {
cache.unmark_dirty();
return Err(Error::FullStorage);
}
// If there is a partial open page, we try to write in that first if there is enough space
let next_page_to_use = if let Some(partial_open_page) =
find_first_page(flash, flash_range.clone(), cache, 0, PageState::PartialOpen).await?
{
// We found a partial open page, but at this point it's relatively cheap to do a consistency check
if !get_page_state(
flash,
flash_range.clone(),
cache,
next_page::<S>(flash_range.clone(), partial_open_page),
)
.await?
.is_open()
{
// Oh oh, the next page which serves as the buffer page is not open. We're corrupt.
// This likely happened because of an unexpected shutdown during data migration from the
// then new buffer page to the new partial open page.
// The repair function should be able to repair this.
return Err(Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
});
}
// We've got to search where the free space is since the page starts with items present already
let page_data_start_address =
calculate_page_address::<S>(flash_range.clone(), partial_open_page)
+ S::WORD_SIZE as u32;
let page_data_end_address =
calculate_page_end_address::<S>(flash_range.clone(), partial_open_page)
- S::WORD_SIZE as u32;
let key_len = key.serialize_into(data_buffer)?;
let item_data_length = key_len
+ item
.serialize_into(&mut data_buffer[key_len..])
.map_err(Error::SerializationError)?;
if item_data_length > u16::MAX as usize
|| item_data_length
> calculate_page_size::<S>()
.saturating_sub(ItemHeader::data_address::<S>(0) as usize)
{
cache.unmark_dirty();
return Err(Error::ItemTooBig);
}
let free_spot_address = find_next_free_item_spot(
flash,
flash_range.clone(),
cache,
page_data_start_address,
page_data_end_address,
item_data_length as u32,
)
.await?;
match free_spot_address {
Some(free_spot_address) => {
cache.notice_key_location(key, free_spot_address, true);
Item::write_new(
flash,
flash_range.clone(),
cache,
free_spot_address,
&data_buffer[..item_data_length],
)
.await?;
cache.unmark_dirty();
return Ok(());
}
None => {
// The item doesn't fit here, so we need to close this page and move to the next
close_page(flash, flash_range.clone(), cache, partial_open_page).await?;
Some(next_page::<S>(flash_range.clone(), partial_open_page))
}
}
} else {
None
};
// If we get here, there was no partial page found or the partial page has now been closed because the item didn't fit.
// If there was a partial page, then we need to look at the next page. It's supposed to be open since it was the previous empty buffer page.
// The new buffer page has to be emptied if it was closed.
// If there was no partial page, we just use the first open page.
match next_page_to_use {
Some(next_page_to_use) => {
let next_page_state =
get_page_state(flash, flash_range.clone(), cache, next_page_to_use).await?;
if !next_page_state.is_open() {
// What was the previous buffer page was not open...
return Err(Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
});
}
// Since we're gonna write data here, let's already partially close the page
// This could be done after moving the data, but this is more robust in the
// face of shutdowns and cancellations
partial_close_page(flash, flash_range.clone(), cache, next_page_to_use).await?;
let next_buffer_page = next_page::<S>(flash_range.clone(), next_page_to_use);
let next_buffer_page_state =
get_page_state(flash, flash_range.clone(), cache, next_buffer_page).await?;
if !next_buffer_page_state.is_open() {
migrate_items::<K, _>(
flash,
flash_range.clone(),
cache,
data_buffer,
next_buffer_page,
next_page_to_use,
)
.await?;
}
}
None => {
// There's no partial open page, so we just gotta turn the first open page into a partial open one
let first_open_page =
match find_first_page(flash, flash_range.clone(), cache, 0, PageState::Open)
.await?
{
Some(first_open_page) => first_open_page,
None => {
// Uh oh, no open pages.
// Something has gone wrong.
// We should never get here.
return Err(Error::Corrupted {
#[cfg(feature = "_test")]
backtrace: std::backtrace::Backtrace::capture(),
});
}
};
partial_close_page(flash, flash_range.clone(), cache, first_open_page).await?;
}
}
// If we get here, we just freshly partially closed a new page, so the next loop iteration should succeed.
recursion_level += 1;
}
}
/// Fully remove an item. Additional calls to fetch with the same key will return None until
/// a new one is stored again.
///
/// <div class="warning">
/// This is really slow!
///
/// All items in flash have to be read and deserialized to find the items with the key.
/// This is unlikely to be cached well.
///
/// Alternatively, e.g. when you don't have a [MultiwriteNorFlash] flash, you could store your value inside an Option
/// and store the value `None` to mark it as erased.
/// </div>
///
/// <div class="warning">
///
/// *You are required to, on a given flash range, use the same [Key] type every time. You are allowed to use*
/// *multiple [Value] types. See the module-level docs for more information about this.*
///
/// Also watch out for using integers. This function will take any integer and it's easy to pass the wrong type.
///
/// </div>
pub async fn remove_item<K: Key, S: MultiwriteNorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &mut [u8],
search_key: &K,
) -> Result<(), Error<S::Error>> {
run_with_auto_repair!(
function = remove_item_inner::<K, _>(
flash,
flash_range.clone(),
cache,
data_buffer,
Some(search_key)
)
.await,
repair = try_repair::<K, _>(flash, flash_range.clone(), cache, data_buffer).await?
)
}
/// Fully remove all stored items. Additional calls to fetch with any key will return None until
/// new items are stored again.
///
/// <div class="warning">
/// This might be really slow! This doesn't simply erase flash, but goes through all items and marks them as deleted.
/// This is better for flash endurance.
///
/// You might want to simply erase the flash range, e.g. if your flash does not implement [MultiwriteNorFlash].
/// Consider using the helper method for that: [crate::erase_all].
/// </div>
///
/// <div class="warning">
///
/// *You are required to, on a given flash range, use the same [Key] type every time. You are allowed to use*
/// *multiple [Value] types. See the module-level docs for more information about this.*
///
/// </div>
pub async fn remove_all_items<K: Key, S: MultiwriteNorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &mut [u8],
) -> Result<(), Error<S::Error>> {
run_with_auto_repair!(
function =
remove_item_inner::<K, _>(flash, flash_range.clone(), cache, data_buffer, None).await,
repair = try_repair::<K, _>(flash, flash_range.clone(), cache, data_buffer).await?
)
}
/// If `search_key` is None, then all items will be removed
async fn remove_item_inner<K: Key, S: MultiwriteNorFlash>(
flash: &mut S,
flash_range: Range<u32>,
cache: &mut impl KeyCacheImpl<K>,
data_buffer: &mut [u8],
search_key: Option<&K>,
) -> Result<(), Error<S::Error>> {
if let Some(key) = &search_key {
cache.notice_key_erased(key);
} else {
cache.invalidate_cache_state();
}
// Search for the last used page. We're gonna erase from the one after this first.
// If we get an early shutoff or cancellation, this will make it so that we don't return
// an old version of the key on the next fetch.
let last_used_page =
find_first_page(flash, flash_range.clone(), cache, 0, PageState::PartialOpen)
.await?
.unwrap_or_default();
// Go through all the pages
for page_index in get_pages::<S>(
flash_range.clone(),
next_page::<S>(flash_range.clone(), last_used_page),
) {
if get_page_state(flash, flash_range.clone(), cache, page_index)
.await?
.is_open()
{
// This page is open, we don't have to check it
continue;
}
let page_data_start_address =
calculate_page_address::<S>(flash_range.clone(), page_index) + S::WORD_SIZE as u32;
let page_data_end_address =
calculate_page_end_address::<S>(flash_range.clone(), page_index) - S::WORD_SIZE as u32;
// Go through all items on the page
let mut item_headers = ItemHeaderIter::new(page_data_start_address, page_data_end_address);
while let (Some(item_header), item_address) = item_headers.next(flash).await? {
let item = item_header
.read_item(flash, data_buffer, item_address, page_data_end_address)
.await?;
match item {
item::MaybeItem::Corrupted(_, _) => continue,
item::MaybeItem::Erased(_, _) => continue,
item::MaybeItem::Present(item) => {
let item_match = match search_key {
Some(search_key) => K::deserialize_from(item.data())?.0 == *search_key,
_ => true,
};
// If this item has the same key as the key we're trying to erase, then erase the item.
// But keep going! We need to erase everything.
if item_match {
item.header
.erase_data(flash, flash_range.clone(), cache, item_address)
.await?;
}
}
}
}
}
// We're done, we now know the cache is in a good state
cache.unmark_dirty();
Ok(())
}
/// Anything implementing this trait can be used as a key in the map functions.
///
/// It provides a way to serialize and deserialize the key.
///
/// The `Eq` bound is used because we need to be able to compare keys and the
/// `Clone` bound helps us pass the key around.
///
/// The key cannot have a lifetime like the [Value]
pub trait Key: Eq + Clone + Sized {
/// Serialize the key into the given buffer.
/// The serialized size is returned.
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError>;
/// Deserialize the key from the given buffer.
/// The key is returned together with the serialized length.
fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError>;
/// Get the length of the key from the buffer.
/// This is an optimized version of [Self::deserialize_from] that doesn't have to deserialize everything.
fn get_len(buffer: &[u8]) -> Result<usize, SerializationError> {
Self::deserialize_from(buffer).map(|(_, len)| len)
}
}
macro_rules! impl_key_num {
($int:ty) => {
impl Key for $int {
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
let len = size_of::<Self>();
if buffer.len() < len {
return Err(SerializationError::BufferTooSmall);
}
buffer[..len].copy_from_slice(&self.to_le_bytes());
Ok(len)
}
fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError> {
let len = size_of::<Self>();
if buffer.len() < len {
return Err(SerializationError::BufferTooSmall);
}
Ok((
Self::from_le_bytes(buffer[..len].try_into().unwrap()),
size_of::<Self>(),
))
}
fn get_len(_buffer: &[u8]) -> Result<usize, SerializationError> {
Ok(size_of::<Self>())
}
}
};
}
impl_key_num!(u8);
impl_key_num!(u16);
impl_key_num!(u32);
impl_key_num!(u64);
impl_key_num!(u128);
impl_key_num!(i8);
impl_key_num!(i16);
impl_key_num!(i32);
impl_key_num!(i64);
impl_key_num!(i128);
impl<const N: usize> Key for [u8; N] {
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
if buffer.len() < N {
return Err(SerializationError::BufferTooSmall);
}
buffer[..N].copy_from_slice(self);
Ok(N)
}
fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError> {
if buffer.len() < N {
return Err(SerializationError::BufferTooSmall);
}
Ok((buffer[..N].try_into().unwrap(), N))
}
fn get_len(_buffer: &[u8]) -> Result<usize, SerializationError> {
Ok(N)
}
}
/// The trait that defines how map values are serialized and deserialized.
///
/// It also carries a lifetime so that zero-copy deserialization is supported.
/// Zero-copy serialization is not supported due to technical restrictions.
pub trait Value<'a> {
/// Serialize the value into the given buffer. If everything went ok, this function returns the length
/// of the used part of the buffer.
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError>;
/// Deserialize the value from the buffer. Because of the added lifetime, the implementation can borrow from the
/// buffer which opens up some zero-copy possibilities.
///
/// The buffer will be the same length as the serialize function returned for this value. Though note that the length
/// is written from flash, so bitflips can affect that (though the length is separately crc-protected) and the key deserialization might
/// return a wrong length.
fn deserialize_from(buffer: &'a [u8]) -> Result<Self, SerializationError>
where
Self: Sized;
}
impl<'a> Value<'a> for bool {
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
<u8 as Value>::serialize_into(&(*self as u8), buffer)
}
fn deserialize_from(buffer: &'a [u8]) -> Result<Self, SerializationError>
where
Self: Sized,
{
Ok(<u8 as Value>::deserialize_from(buffer)? != 0)
}
}
impl<'a, T: Value<'a>> Value<'a> for Option<T> {
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
if let Some(val) = self {
<bool as Value>::serialize_into(&true, buffer)?;
<T as Value>::serialize_into(val, buffer)