1use crate::bitfields::{HeaderFields, PayloadFields};
8use crate::block_index::BlockIndex;
9use crate::block_type::BlockType;
10use crate::container::{ReadBytes, WriteBytes};
11use crate::error::Error;
12use crate::{constants, utils};
13use byteorder::{ByteOrder, LittleEndian};
14use num_derive::FromPrimitive;
15use num_traits::FromPrimitive;
16use std::cmp::min;
17use std::marker::PhantomData;
18use std::ops::{Deref, DerefMut};
19use std::sync::atomic::{Ordering, fence};
20
21pub use diagnostics_hierarchy::ArrayFormat;
22
23#[derive(Clone, Debug, PartialEq, Eq, FromPrimitive)]
25#[repr(u8)]
26pub enum LinkNodeDisposition {
27 Child = 0,
28 Inline = 1,
29 Blob = 2,
30}
31
32#[derive(Debug, PartialEq, Eq, FromPrimitive)]
34#[repr(u8)]
35pub enum PropertyFormat {
36 String = 0,
37 Bytes = 1,
38 StringReference = 2,
39}
40
41#[derive(Debug, Clone)]
43pub struct Block<T, Kind> {
44 pub(crate) index: BlockIndex,
45 pub(crate) container: T,
46 _phantom: PhantomData<Kind>,
47}
48
49impl<T: Deref<Target = Q>, Q, K> Block<T, K> {
50 #[inline]
52 pub(crate) fn new(container: T, index: BlockIndex) -> Self {
53 Block { container, index, _phantom: PhantomData }
54 }
55}
56
57pub trait BlockAccessorExt: ReadBytes + Sized {
58 #[inline]
59 fn maybe_block_at<K: BlockKind>(&self, index: BlockIndex) -> Option<Block<&Self, K>> {
60 let block = Block::new(self, index);
61 let block_type = HeaderFields::block_type(&block);
62 if block_type != K::block_type() as u8 {
63 return None;
64 }
65 Some(block)
66 }
67
68 #[cfg_attr(debug_assertions, track_caller)]
69 #[inline]
70 fn block_at_unchecked<K: BlockKind>(&self, index: BlockIndex) -> Block<&Self, K> {
71 Block::new(self, index)
72 }
75
76 #[inline]
77 fn block_at(&self, index: BlockIndex) -> Block<&Self, Unknown> {
78 Block::new(self, index)
79 }
80}
81
82pub trait BlockAccessorMutExt: WriteBytes + ReadBytes + Sized {
83 #[inline]
84 fn maybe_block_at_mut<K: BlockKind>(
85 &mut self,
86 index: BlockIndex,
87 ) -> Option<Block<&mut Self, K>> {
88 let block = Block::new(self, index);
89 let block_type = HeaderFields::block_type(&block);
90 if block_type != K::block_type() as u8 {
91 return None;
92 }
93 Some(block)
94 }
95
96 #[inline]
97 fn block_at_unchecked_mut<K: BlockKind>(&mut self, index: BlockIndex) -> Block<&mut Self, K> {
98 Block::new(self, index)
99 }
100
101 #[inline]
102 fn block_at_mut(&mut self, index: BlockIndex) -> Block<&mut Self, Unknown> {
103 Block::new(self, index)
104 }
105}
106
107impl<T> BlockAccessorExt for T where T: ReadBytes {}
108impl<T> BlockAccessorMutExt for T where T: WriteBytes + ReadBytes {}
109
110mod private {
111 pub trait Sealed {}
112}
113
114pub trait BlockKind: private::Sealed {
115 fn block_type() -> BlockType;
116}
117
118macro_rules! block_kind {
119 ([$(($name:ident, $block_type:ident)),*]) => {
120 $(
121 #[derive(Copy, Clone, Debug)]
122 pub struct $name;
123 impl BlockKind for $name {
124 fn block_type() -> BlockType {
125 BlockType::$block_type
126 }
127 }
128 impl private::Sealed for $name {}
129 )*
130 }
131}
132
133block_kind!([
134 (Header, Header),
135 (Double, DoubleValue),
136 (Int, IntValue),
137 (Uint, UintValue),
138 (Bool, BoolValue),
139 (Buffer, BufferValue),
140 (Extent, Extent),
141 (StringRef, StringReference),
142 (Link, LinkValue),
143 (Node, NodeValue),
144 (Free, Free),
145 (Tombstone, Tombstone),
146 (Reserved, Reserved),
147 (Name, Name)
148]);
149
150#[derive(Copy, Clone, Debug)]
151pub struct Unknown;
152impl private::Sealed for Unknown {}
153impl BlockKind for Unknown {
154 #[track_caller]
155 fn block_type() -> BlockType {
156 panic!("implementation must not call into Unknown::block_type()")
157 }
158}
159
160#[derive(Copy, Clone, Debug)]
161pub struct Array<T>(PhantomData<T>);
162impl<T> private::Sealed for Array<T> {}
163impl<T: ArraySlotKind> BlockKind for Array<T> {
164 fn block_type() -> BlockType {
165 BlockType::ArrayValue
166 }
167}
168
169pub trait ValueBlockKind: BlockKind {}
170
171macro_rules! impl_value_block {
172 ([$($name:ident),*]) => {
173 $(
174 impl ValueBlockKind for $name {}
175 )*
176 }
177}
178
179impl_value_block!([Node, Int, Uint, Double, Buffer, Link, Bool]);
180impl<T: ArraySlotKind> ValueBlockKind for Array<T> {}
181
182pub trait ArraySlotKind: BlockKind {
183 fn array_entry_type_size() -> usize;
184}
185
186impl ArraySlotKind for Double {
187 fn array_entry_type_size() -> usize {
188 std::mem::size_of::<f64>()
189 }
190}
191
192impl ArraySlotKind for Int {
193 fn array_entry_type_size() -> usize {
194 std::mem::size_of::<i64>()
195 }
196}
197
198impl ArraySlotKind for Uint {
199 fn array_entry_type_size() -> usize {
200 std::mem::size_of::<u64>()
201 }
202}
203
204impl ArraySlotKind for StringRef {
205 fn array_entry_type_size() -> usize {
206 std::mem::size_of::<u32>()
207 }
208}
209
210impl ArraySlotKind for Unknown {
211 #[track_caller]
212 fn array_entry_type_size() -> usize {
213 panic!("Implementation must not get the size of Unknown");
214 }
215}
216
217impl<T: Deref<Target = Q>, Q: ReadBytes, K: BlockKind> Block<T, K> {
218 pub fn index(&self) -> BlockIndex {
220 self.index
221 }
222
223 pub fn order(&self) -> u8 {
225 HeaderFields::order(self)
226 }
227
228 pub fn block_type(&self) -> Option<BlockType> {
230 let block_type = self.block_type_raw();
231 BlockType::from_u8(block_type)
232 }
233
234 pub fn block_type_raw(&self) -> u8 {
236 HeaderFields::block_type(self)
237 }
238
239 pub(crate) fn payload_offset(&self) -> usize {
241 self.index.offset() + constants::HEADER_SIZE_BYTES
242 }
243
244 pub(crate) fn header_offset(&self) -> usize {
246 self.index.offset()
247 }
248}
249
250impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Unknown> {
251 pub fn cast<K: BlockKind>(self) -> Option<Block<T, K>> {
252 let block_type = HeaderFields::block_type(&self);
253 if block_type != K::block_type() as u8 {
254 return None;
255 }
256 Some(Block { container: self.container, index: self.index, _phantom: PhantomData })
257 }
258
259 pub fn cast_unchecked<K: BlockKind>(self) -> Block<T, K> {
260 Block { container: self.container, index: self.index, _phantom: PhantomData }
261 }
262}
263
264impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Array<Unknown>> {
265 pub fn cast_array<K: ArraySlotKind>(self) -> Option<Block<T, Array<K>>> {
266 let entry_type = self.entry_type()?;
267 if entry_type != K::block_type() {
268 return None;
269 }
270 Some(Block { container: self.container, index: self.index, _phantom: PhantomData })
271 }
272
273 pub fn cast_array_unchecked<K: BlockKind>(self) -> Block<T, Array<K>> {
274 Block { container: self.container, index: self.index, _phantom: PhantomData }
275 }
276}
277
278impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Header> {
279 pub fn parse_header_with_magic(container: T, expected_magic: u32) -> Option<Self> {
305 if container.len() < constants::MIN_ORDER_SIZE {
306 return None;
307 }
308 let block = Block::new(container, BlockIndex::HEADER);
309 if HeaderFields::block_type(&block) != BlockType::Header as u8 {
310 return None;
311 }
312 if block.magic_number() != expected_magic
313 || block.version() > constants::HEADER_VERSION_NUMBER
314 {
315 return None;
316 }
317 Some(block)
318 }
319
320 pub fn parse_inspect_header(container: T) -> Option<Self> {
325 Self::parse_header_with_magic(container, constants::HEADER_MAGIC_NUMBER)
326 }
327
328 pub fn parse_blob_header(container: T) -> Option<Self> {
333 Self::parse_header_with_magic(container, constants::BLOB_HEADER_MAGIC_NUMBER)
334 }
335
336 pub fn magic_number(&self) -> u32 {
338 HeaderFields::header_magic(self)
339 }
340
341 pub fn version(&self) -> u32 {
343 HeaderFields::header_version(self)
344 }
345
346 pub fn generation_count(&self) -> u64 {
348 PayloadFields::value(self)
349 }
350
351 pub fn unlocked_generation_count(&self) -> Option<u64> {
353 let count = self.generation_count();
354 (count & 1 == 0).then_some(count)
355 }
356
357 pub fn vmo_size(&self) -> Result<Option<u32>, Error> {
360 if self.order() != constants::HEADER_ORDER {
361 return Ok(None);
362 }
363 let offset = (self.index + 1).offset();
364 let value = self.container.get_value(offset).ok_or(Error::InvalidOffset(offset))?;
365 Ok(Some(value))
366 }
367
368 pub fn is_frozen(&self) -> bool {
370 self.generation_count() == constants::VMO_FROZEN
371 }
372
373 pub fn is_locked(&self) -> bool {
375 PayloadFields::value(self) & 1 == 1
376 }
377
378 #[doc(hidden)]
381 #[cfg_attr(debug_assertions, track_caller)]
382 pub fn check_locked(&self, value: bool) {
383 if cfg!(any(debug_assertions, test)) {
384 let generation_count = PayloadFields::value(self);
385 if (generation_count & 1 == 1) != value {
386 panic!("Expected lock state: {value}")
387 }
388 }
389 }
390}
391
392impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Double> {
393 pub fn value(&self) -> f64 {
395 f64::from_bits(PayloadFields::value(self))
396 }
397}
398
399impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Int> {
400 pub fn value(&self) -> i64 {
402 i64::from_le_bytes(PayloadFields::value(self).to_le_bytes())
403 }
404}
405
406impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Uint> {
407 pub fn value(&self) -> u64 {
409 PayloadFields::value(self)
410 }
411}
412
413impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Bool> {
414 pub fn value(&self) -> bool {
416 PayloadFields::value(self) != 0
417 }
418}
419
420impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Buffer> {
421 pub fn extent_index(&self) -> BlockIndex {
423 PayloadFields::property_extent_index(self).into()
424 }
425
426 pub fn total_length(&self) -> usize {
428 PayloadFields::property_total_length(self) as usize
429 }
430
431 pub fn format(&self) -> Option<PropertyFormat> {
433 let raw_format = PayloadFields::property_flags(self);
434 PropertyFormat::from_u8(raw_format)
435 }
436
437 pub fn format_raw(&self) -> u8 {
439 PayloadFields::property_flags(self)
440 }
441}
442
443impl<'a, T: Deref<Target = Q>, Q: ReadBytes + 'a> Block<T, StringRef> {
444 pub fn total_length(&self) -> usize {
446 PayloadFields::property_total_length(self) as usize
447 }
448
449 pub fn next_extent(&self) -> BlockIndex {
451 HeaderFields::extent_next_index(self).into()
452 }
453
454 pub fn reference_count(&self) -> u32 {
456 HeaderFields::string_reference_count(self)
457 }
458
459 pub fn inline_data(&'a self) -> Result<&'a [u8], Error> {
461 let max_len_inlined = utils::payload_size_for_order(self.order())
462 - constants::STRING_REFERENCE_TOTAL_LENGTH_BYTES;
463 let length = self.total_length();
464 let offset = self.payload_offset() + constants::STRING_REFERENCE_TOTAL_LENGTH_BYTES;
465 let bytes = self
466 .container
467 .get_slice_at(offset, min(length, max_len_inlined))
468 .ok_or(Error::InvalidOffset(offset))?;
469 Ok(bytes)
470 }
471}
472
473impl<'a, T: Deref<Target = Q>, Q: ReadBytes + 'a> Block<T, Extent> {
474 pub fn next_extent(&self) -> BlockIndex {
476 HeaderFields::extent_next_index(self).into()
477 }
478
479 pub fn contents(&'a self) -> Result<&'a [u8], Error> {
481 let length = utils::payload_size_for_order(self.order());
482 let offset = self.payload_offset();
483 self.container.get_slice_at(offset, length).ok_or(Error::InvalidOffset(offset))
484 }
485}
486
487impl<T: Deref<Target = Q>, Q: ReadBytes, S: ArraySlotKind> Block<T, Array<S>> {
488 pub fn format(&self) -> Option<ArrayFormat> {
490 let raw_flags = PayloadFields::array_flags(self);
491 ArrayFormat::from_u8(raw_flags)
492 }
493
494 pub fn slots(&self) -> usize {
496 PayloadFields::array_slots_count(self) as usize
497 }
498
499 pub fn capacity(&self) -> Option<usize> {
501 self.entry_type_size().map(|size| array_capacity(size, self.order()))
502 }
503
504 pub fn entry_type(&self) -> Option<BlockType> {
506 let array_type_raw = PayloadFields::array_entry_type(self);
507 BlockType::from_u8(array_type_raw).filter(|array_type| array_type.is_valid_for_array())
508 }
509
510 pub fn entry_type_raw(&self) -> u8 {
512 PayloadFields::array_entry_type(self)
513 }
514
515 pub fn entry_type_size(&self) -> Option<usize> {
516 self.entry_type().and_then(|entry_type| match entry_type {
517 BlockType::IntValue => Some(Int::array_entry_type_size()),
518 BlockType::UintValue => Some(Uint::array_entry_type_size()),
519 BlockType::DoubleValue => Some(Double::array_entry_type_size()),
520 BlockType::StringReference => Some(StringRef::array_entry_type_size()),
521 _ => None,
522 })
523 }
524}
525
526impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Array<StringRef>> {
527 pub fn get_string_index_at(&self, slot_index: usize) -> Option<BlockIndex> {
528 if slot_index >= self.slots() {
529 return None;
530 }
531 let offset = (self.index + 1).offset() + slot_index * StringRef::array_entry_type_size();
532 self.container.get_value(offset).map(BlockIndex::new)
533 }
534}
535
536impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Array<Int>> {
537 pub fn get(&self, slot_index: usize) -> Option<i64> {
539 if slot_index >= self.slots() {
540 return None;
541 }
542 let offset = (self.index + 1).offset() + slot_index * 8;
543 self.container.get_value(offset)
544 }
545}
546
547impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Array<Double>> {
548 pub fn get(&self, slot_index: usize) -> Option<f64> {
550 if slot_index >= self.slots() {
551 return None;
552 }
553 let offset = (self.index + 1).offset() + slot_index * 8;
554 self.container.get_value(offset)
555 }
556}
557
558impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Array<Uint>> {
559 pub fn get(&self, slot_index: usize) -> Option<u64> {
561 if slot_index >= self.slots() {
562 return None;
563 }
564 let offset = (self.index + 1).offset() + slot_index * 8;
565 self.container.get_value(offset)
566 }
567}
568
569impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Link> {
570 pub fn content_index(&self) -> BlockIndex {
572 PayloadFields::content_index(self).into()
573 }
574
575 pub fn link_node_disposition(&self) -> Option<LinkNodeDisposition> {
577 let flag = PayloadFields::disposition_flags(self);
578 LinkNodeDisposition::from_u8(flag)
579 }
580}
581
582impl<T: Deref<Target = Q>, Q: ReadBytes, K: ValueBlockKind> Block<T, K> {
583 pub fn name_index(&self) -> BlockIndex {
585 HeaderFields::value_name_index(self).into()
586 }
587
588 pub fn parent_index(&self) -> BlockIndex {
590 HeaderFields::value_parent_index(self).into()
591 }
592}
593
594impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Node> {
595 pub fn child_count(&self) -> u64 {
597 PayloadFields::value(self)
598 }
599}
600
601impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Tombstone> {
602 pub fn child_count(&self) -> u64 {
604 PayloadFields::value(self)
605 }
606}
607
608impl<T: Deref<Target = Q>, Q: ReadBytes> Block<T, Free> {
609 pub fn free_next_index(&self) -> BlockIndex {
611 HeaderFields::free_next_index(self).into()
612 }
613}
614
615impl<'a, T: Deref<Target = Q>, Q: ReadBytes + 'a> Block<T, Name> {
616 pub fn length(&self) -> usize {
618 HeaderFields::name_length(self).into()
619 }
620
621 pub fn contents(&'a self) -> Result<&'a str, Error> {
623 let length = self.length();
624 let offset = self.payload_offset();
625 let bytes =
626 self.container.get_slice_at(offset, length).ok_or(Error::InvalidOffset(offset))?;
627 std::str::from_utf8(bytes).map_err(|_| Error::NameNotUtf8)
628 }
629}
630
631impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes, K: BlockKind>
632 Block<T, K>
633{
634 pub fn become_free(mut self, next: BlockIndex) -> Block<T, Free> {
636 HeaderFields::set_free_reserved(&mut self, 0);
637 HeaderFields::set_block_type(&mut self, BlockType::Free as u8);
638 HeaderFields::set_free_next_index(&mut self, *next);
639 HeaderFields::set_free_empty(&mut self, 0);
640 Block { index: self.index, container: self.container, _phantom: PhantomData }
641 }
642}
643
644impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes, K: BlockKind>
645 Block<T, K>
646{
647 pub fn set_order(&mut self, order: u8) -> Result<(), Error> {
649 if order >= constants::NUM_ORDERS {
650 return Err(Error::InvalidBlockOrder(order));
651 }
652 HeaderFields::set_order(self, order);
653 Ok(())
654 }
655
656 fn write_payload_from_bytes(&mut self, bytes: &[u8]) {
658 let offset = self.payload_offset();
659 self.container.copy_from_slice_at(offset, bytes);
660 }
661}
662
663impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Free> {
664 pub fn free(
666 container: T,
667 index: BlockIndex,
668 order: u8,
669 next_free: BlockIndex,
670 ) -> Result<Block<T, Free>, Error> {
671 if order >= constants::NUM_ORDERS {
672 return Err(Error::InvalidBlockOrder(order));
673 }
674 let mut block = Block::new(container, index);
675 HeaderFields::set_value(&mut block, 0);
676 HeaderFields::set_order(&mut block, order);
677 HeaderFields::set_block_type(&mut block, BlockType::Free as u8);
678 HeaderFields::set_free_next_index(&mut block, *next_free);
679 Ok(block)
680 }
681
682 pub fn become_reserved(mut self) -> Block<T, Reserved> {
684 HeaderFields::set_block_type(&mut self, BlockType::Reserved as u8);
685 HeaderFields::set_reserved_empty(&mut self, 0);
686 Block { index: self.index, container: self.container, _phantom: PhantomData }
687 }
688
689 pub fn set_free_next_index(&mut self, next_free: BlockIndex) {
691 HeaderFields::set_free_next_index(self, *next_free);
692 }
693}
694
695impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Reserved> {
696 fn become_header_with_magic(
707 mut self,
708 magic: u32,
709 size: usize,
710 ) -> Result<Block<T, Header>, Error> {
711 self.index = BlockIndex::HEADER;
712 HeaderFields::set_order(&mut self, constants::HEADER_ORDER);
713 HeaderFields::set_block_type(&mut self, BlockType::Header as u8);
714 HeaderFields::set_header_magic(&mut self, magic);
715 HeaderFields::set_header_version(&mut self, constants::HEADER_VERSION_NUMBER);
716 PayloadFields::set_value(&mut self, 0);
717 let mut this =
718 Block { index: self.index, container: self.container, _phantom: PhantomData };
719 this.set_vmo_size(size.try_into().unwrap())?;
721 Ok(this)
722 }
723
724 pub fn become_inspect_header(self, size: usize) -> Result<Block<T, Header>, Error> {
727 self.become_header_with_magic(constants::HEADER_MAGIC_NUMBER, size)
728 }
729
730 pub fn become_blob_header(self, size: usize) -> Result<Block<T, Header>, Error> {
733 self.become_header_with_magic(constants::BLOB_HEADER_MAGIC_NUMBER, size)
734 }
735
736 pub fn become_extent(mut self, next_extent_index: BlockIndex) -> Block<T, Extent> {
738 HeaderFields::set_block_type(&mut self, BlockType::Extent as u8);
739 HeaderFields::set_extent_next_index(&mut self, *next_extent_index);
740 Block { index: self.index, container: self.container, _phantom: PhantomData }
741 }
742
743 pub fn become_double_value(
745 mut self,
746 value: f64,
747 name_index: BlockIndex,
748 parent_index: BlockIndex,
749 ) -> Block<T, Double> {
750 self.write_value_header(BlockType::DoubleValue, name_index, parent_index);
751 let mut this =
752 Block { index: self.index, container: self.container, _phantom: PhantomData::<Double> };
753 this.set(value);
754 this
755 }
756
757 pub fn become_int_value(
759 mut self,
760 value: i64,
761 name_index: BlockIndex,
762 parent_index: BlockIndex,
763 ) -> Block<T, Int> {
764 self.write_value_header(BlockType::IntValue, name_index, parent_index);
765 let mut this =
766 Block { index: self.index, container: self.container, _phantom: PhantomData::<Int> };
767 this.set(value);
768 this
769 }
770
771 pub fn become_uint_value(
773 mut self,
774 value: u64,
775 name_index: BlockIndex,
776 parent_index: BlockIndex,
777 ) -> Block<T, Uint> {
778 self.write_value_header(BlockType::UintValue, name_index, parent_index);
779 let mut this =
780 Block { index: self.index, container: self.container, _phantom: PhantomData::<Uint> };
781 this.set(value);
782 this
783 }
784
785 pub fn become_bool_value(
787 mut self,
788 value: bool,
789 name_index: BlockIndex,
790 parent_index: BlockIndex,
791 ) -> Block<T, Bool> {
792 self.write_value_header(BlockType::BoolValue, name_index, parent_index);
793 let mut this =
794 Block { index: self.index, container: self.container, _phantom: PhantomData::<Bool> };
795 this.set(value);
796 this
797 }
798
799 pub fn become_node(
801 mut self,
802 name_index: BlockIndex,
803 parent_index: BlockIndex,
804 ) -> Block<T, Node> {
805 self.write_value_header(BlockType::NodeValue, name_index, parent_index);
806 PayloadFields::set_value(&mut self, 0);
807 Block { index: self.index, container: self.container, _phantom: PhantomData }
808 }
809
810 pub fn become_property(
812 mut self,
813 name_index: BlockIndex,
814 parent_index: BlockIndex,
815 format: PropertyFormat,
816 ) -> Block<T, Buffer> {
817 self.write_value_header(BlockType::BufferValue, name_index, parent_index);
818 PayloadFields::set_value(&mut self, 0);
819 PayloadFields::set_property_flags(&mut self, format as u8);
820 Block { index: self.index, container: self.container, _phantom: PhantomData }
821 }
822
823 pub fn become_string_reference(mut self) -> Block<T, StringRef> {
826 HeaderFields::set_block_type(&mut self, BlockType::StringReference as u8);
827 HeaderFields::set_extent_next_index(&mut self, *BlockIndex::EMPTY);
828 HeaderFields::set_string_reference_count(&mut self, 0);
829 Block { index: self.index, container: self.container, _phantom: PhantomData }
830 }
831
832 pub fn become_name(mut self, name: &str) -> Block<T, Name> {
834 let max_len = utils::payload_size_for_order(self.order());
835 let valid_len = name.floor_char_boundary(max_len);
836 let bytes = &name.as_bytes()[..valid_len];
837 HeaderFields::set_block_type(&mut self, BlockType::Name as u8);
838 HeaderFields::set_name_length(&mut self, u16::from_usize(bytes.len()).unwrap());
840 self.write_payload_from_bytes(bytes);
841 Block { index: self.index, container: self.container, _phantom: PhantomData }
842 }
843
844 pub fn become_link(
846 mut self,
847 name_index: BlockIndex,
848 parent_index: BlockIndex,
849 content_index: BlockIndex,
850 disposition_flags: LinkNodeDisposition,
851 ) -> Block<T, Link> {
852 self.write_value_header(BlockType::LinkValue, name_index, parent_index);
853 PayloadFields::set_value(&mut self, 0);
854 PayloadFields::set_content_index(&mut self, *content_index);
855 PayloadFields::set_disposition_flags(&mut self, disposition_flags as u8);
856 Block { index: self.index, container: self.container, _phantom: PhantomData }
857 }
858
859 pub fn become_array_value<S: ArraySlotKind>(
861 mut self,
862 slots: usize,
863 format: ArrayFormat,
864 name_index: BlockIndex,
865 parent_index: BlockIndex,
866 ) -> Result<Block<T, Array<S>>, Error> {
867 if S::block_type() == BlockType::StringReference && format != ArrayFormat::Default {
868 return Err(Error::InvalidArrayType(self.index));
869 }
870 let order = self.order();
871 let max_capacity = max_array_capacity::<S>(order);
872
873 if slots > max_capacity {
874 return Err(Error::array_capacity_exceeded(slots, order, max_capacity));
875 }
876 self.write_value_header(BlockType::ArrayValue, name_index, parent_index);
877 PayloadFields::set_value(&mut self, 0);
878 PayloadFields::set_array_entry_type(&mut self, S::block_type() as u8);
879 PayloadFields::set_array_flags(&mut self, format as u8);
880 PayloadFields::set_array_slots_count(&mut self, slots as u8);
881 let mut this =
882 Block { index: self.index, container: self.container, _phantom: PhantomData };
883 this.clear(0);
884 Ok(this)
885 }
886
887 #[cfg_attr(debug_assertions, track_caller)]
889 fn write_value_header(
890 &mut self,
891 block_type: BlockType,
892 name_index: BlockIndex,
893 parent_index: BlockIndex,
894 ) {
895 debug_assert!(block_type.is_any_value(), "Unexpected block: {block_type}");
896 HeaderFields::set_block_type(self, block_type as u8);
897 HeaderFields::set_value_name_index(self, *name_index);
898 HeaderFields::set_value_parent_index(self, *parent_index);
899 }
900}
901
902impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Header> {
903 #[doc(hidden)]
906 pub fn set_magic(&mut self, value: u32) {
907 HeaderFields::set_header_magic(self, value);
908 }
909
910 pub fn set_vmo_size(&mut self, size: u32) -> Result<(), Error> {
913 if self.order() != constants::HEADER_ORDER {
914 return Ok(());
915 }
916 self.container.set_value((self.index + 1).offset(), size)
917 }
918
919 pub fn freeze(&mut self) -> u64 {
921 let value = PayloadFields::value(self);
922 PayloadFields::set_value(self, constants::VMO_FROZEN);
923 value
924 }
925
926 pub fn thaw(&mut self, generation: u64) {
928 PayloadFields::set_value(self, generation)
929 }
930
931 pub fn lock(&mut self) {
933 self.check_locked(false);
934 self.increment_generation_count();
935 fence(Ordering::Acquire);
936 }
937
938 pub fn unlock(&mut self) {
940 self.check_locked(true);
941 fence(Ordering::Release);
942 self.increment_generation_count();
943 }
944
945 fn increment_generation_count(&mut self) {
947 let value = PayloadFields::value(self);
948 let new_value = value.wrapping_add(1);
950 PayloadFields::set_value(self, new_value);
951 }
952}
953
954impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Node> {
955 pub fn become_tombstone(mut self) -> Block<T, Tombstone> {
957 HeaderFields::set_block_type(&mut self, BlockType::Tombstone as u8);
958 HeaderFields::set_tombstone_empty(&mut self, 0);
959 Block { index: self.index, container: self.container, _phantom: PhantomData }
960 }
961
962 pub fn set_child_count(&mut self, count: u64) {
964 PayloadFields::set_value(self, count);
965 }
966}
967
968impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes, S: ArraySlotKind>
969 Block<T, Array<S>>
970{
971 pub fn clear(&mut self, start_slot_index: usize) {
973 let array_slots = self.slots() - start_slot_index;
974 let type_size = self.entry_type_size().unwrap();
978 let offset = (self.index + 1).offset() + start_slot_index * type_size;
979 if let Some(slice) = self.container.get_slice_mut_at(offset, array_slots * type_size) {
980 slice.fill(0);
981 }
982 }
983}
984
985impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes>
986 Block<T, Array<StringRef>>
987{
988 pub fn set_string_slot(&mut self, slot_index: usize, string_index: BlockIndex) {
990 if slot_index >= self.slots() {
991 return;
992 }
993 let type_size = StringRef::array_entry_type_size();
995 let _ = self
996 .container
997 .set_value((self.index + 1).offset() + slot_index * type_size, *string_index);
998 }
999}
1000
1001impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Array<Int>> {
1002 pub fn set(&mut self, slot_index: usize, value: i64) {
1004 if slot_index >= self.slots() {
1005 return;
1006 }
1007 let type_size = Int::array_entry_type_size();
1008 let _ = self.container.set_value((self.index + 1).offset() + slot_index * type_size, value);
1009 }
1010}
1011
1012impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes>
1013 Block<T, Array<Double>>
1014{
1015 pub fn set(&mut self, slot_index: usize, value: f64) {
1017 if slot_index >= self.slots() {
1018 return;
1019 }
1020 let type_size = Double::array_entry_type_size();
1021 let _ = self.container.set_value((self.index + 1).offset() + slot_index * type_size, value);
1022 }
1023}
1024
1025impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Array<Uint>> {
1026 pub fn set(&mut self, slot_index: usize, value: u64) {
1028 if slot_index >= self.slots() {
1029 return;
1030 }
1031 let type_size = Uint::array_entry_type_size();
1032 let _ = self.container.set_value((self.index + 1).offset() + slot_index * type_size, value);
1033 }
1034}
1035
1036impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Extent> {
1037 pub fn set_next_index(&mut self, next_extent_index: BlockIndex) {
1039 HeaderFields::set_extent_next_index(self, *next_extent_index);
1040 }
1041
1042 pub fn set_contents(&mut self, value: &[u8]) -> usize {
1044 let order = self.order();
1045 let max_bytes = utils::payload_size_for_order(order);
1046 let mut bytes = value;
1047 if bytes.len() > max_bytes {
1048 bytes = &bytes[..min(bytes.len(), max_bytes)];
1049 }
1050 self.write_payload_from_bytes(bytes);
1051 bytes.len()
1052 }
1053}
1054
1055impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, StringRef> {
1056 pub fn set_next_index(&mut self, next_extent_index: BlockIndex) {
1058 HeaderFields::set_extent_next_index(self, *next_extent_index);
1059 }
1060
1061 pub fn set_total_length(&mut self, length: u32) {
1063 PayloadFields::set_property_total_length(self, length);
1064 }
1065
1066 pub fn increment_ref_count(&mut self) -> Result<(), Error> {
1068 let cur = HeaderFields::string_reference_count(self);
1069 if cur < constants::MAX_REFERENCE_COUNT {
1070 HeaderFields::set_string_reference_count(self, cur + 1);
1071 }
1072 Ok(())
1073 }
1074
1075 pub fn decrement_ref_count(&mut self) -> Result<(), Error> {
1077 let cur = HeaderFields::string_reference_count(self);
1078 if cur < constants::MAX_REFERENCE_COUNT {
1079 let new_count = cur.checked_sub(1).ok_or(Error::InvalidReferenceCount)?;
1080 HeaderFields::set_string_reference_count(self, new_count);
1081 }
1082 Ok(())
1083 }
1084
1085 pub fn write_inline(&mut self, value: &[u8]) -> usize {
1089 let payload_offset = self.payload_offset();
1090 self.set_total_length(value.len() as u32);
1091 let max_len = utils::payload_size_for_order(self.order())
1092 - constants::STRING_REFERENCE_TOTAL_LENGTH_BYTES;
1093 let bytes = min(value.len(), max_len);
1096 let to_inline = &value[..bytes];
1097 self.container.copy_from_slice_at(
1098 payload_offset + constants::STRING_REFERENCE_TOTAL_LENGTH_BYTES,
1099 to_inline,
1100 );
1101 bytes
1102 }
1103}
1104
1105impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Double> {
1106 pub fn set(&mut self, value: f64) {
1108 PayloadFields::set_value(self, value.to_bits());
1109 }
1110}
1111
1112impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Int> {
1113 pub fn set(&mut self, value: i64) {
1115 PayloadFields::set_value(self, LittleEndian::read_u64(&value.to_le_bytes()));
1116 }
1117}
1118
1119impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Uint> {
1120 pub fn set(&mut self, value: u64) {
1122 PayloadFields::set_value(self, value);
1123 }
1124}
1125
1126impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Bool> {
1127 pub fn set(&mut self, value: bool) {
1129 PayloadFields::set_value(self, value as u64);
1130 }
1131}
1132
1133impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Buffer> {
1134 pub fn set_total_length(&mut self, length: u32) {
1136 PayloadFields::set_property_total_length(self, length);
1137 }
1138
1139 pub fn set_extent_index(&mut self, index: BlockIndex) {
1141 PayloadFields::set_property_extent_index(self, *index);
1144 }
1145}
1146
1147impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes> Block<T, Tombstone> {
1148 pub fn set_child_count(&mut self, count: u64) {
1150 PayloadFields::set_value(self, count);
1151 }
1152}
1153
1154impl<T: Deref<Target = Q> + DerefMut<Target = Q>, Q: WriteBytes + ReadBytes, K: ValueBlockKind>
1155 Block<T, K>
1156{
1157 pub fn set_parent(&mut self, new_parent_index: BlockIndex) {
1158 HeaderFields::set_value_parent_index(self, *new_parent_index);
1159 }
1160
1161 pub fn set_name(&mut self, new_name_index: BlockIndex) {
1162 HeaderFields::set_value_name_index(self, *new_name_index);
1163 }
1164}
1165
1166fn max_array_capacity<S: ArraySlotKind>(order: u8) -> usize {
1168 array_capacity(S::array_entry_type_size(), order)
1169}
1170
1171fn array_capacity(slot_size: usize, order: u8) -> usize {
1172 (utils::order_to_size(order)
1173 - constants::HEADER_SIZE_BYTES
1174 - constants::ARRAY_PAYLOAD_METADATA_SIZE_BYTES)
1175 / slot_size
1176}
1177
1178pub mod testing {
1179 use super::*;
1180
1181 pub fn override_header<T: WriteBytes + ReadBytes, K: BlockKind>(
1182 block: &mut Block<&mut T, K>,
1183 value: u64,
1184 ) {
1185 let _ = block.container.set_value(block.header_offset(), value);
1186 }
1187
1188 pub fn override_payload<T: WriteBytes + ReadBytes, K: BlockKind>(
1189 block: &mut Block<&mut T, K>,
1190 value: u64,
1191 ) {
1192 let _ = block.container.set_value(block.payload_offset(), value);
1193 }
1194}
1195
1196#[cfg(test)]
1197mod tests {
1198 use super::*;
1199 use crate::{Container, CopyBytes};
1200
1201 macro_rules! assert_8_bytes {
1202 ($container:ident, $offset:expr, $expected:expr) => {
1203 let slice = $container.get_slice_at($offset, 8).unwrap();
1204 assert_eq!(slice, &$expected);
1205 };
1206 }
1207
1208 #[fuchsia::test]
1209 fn test_new_free() {
1210 let (mut container, _storage) =
1211 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1212 assert!(Block::free(&mut container, 3.into(), constants::NUM_ORDERS, 1.into()).is_err());
1213
1214 let res = Block::free(&mut container, BlockIndex::EMPTY, 3, 1.into());
1215 assert!(res.is_ok());
1216 let block = res.unwrap();
1217 assert_eq!(*block.index(), 0);
1218 assert_eq!(block.order(), 3);
1219 assert_eq!(*block.free_next_index(), 1);
1220 assert_eq!(block.block_type(), Some(BlockType::Free));
1221 assert_8_bytes!(container, 0, [0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]);
1222 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1223 }
1224
1225 #[fuchsia::test]
1226 fn test_set_order() {
1227 let (mut container, _storage) =
1228 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1229 let mut block = Block::free(&mut container, BlockIndex::EMPTY, 1, 1.into()).unwrap();
1230 assert!(block.set_order(3).is_ok());
1231 assert_eq!(block.order(), 3);
1232 }
1233
1234 #[fuchsia::test]
1235 fn test_become_reserved() {
1236 let (mut container, _storage) =
1237 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1238 let block = Block::free(&mut container, BlockIndex::EMPTY, 1, 2.into()).unwrap();
1239 let block = block.become_reserved();
1240 assert_eq!(block.block_type(), Some(BlockType::Reserved));
1241 assert_8_bytes!(container, 0, [0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1242 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1243 }
1244
1245 #[fuchsia::test]
1246 fn test_become_string_reference() {
1247 let (mut container, _storage) =
1248 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1249 let block = get_reserved(&mut container).become_string_reference();
1250 assert_eq!(block.block_type(), Some(BlockType::StringReference));
1251 assert_eq!(*block.next_extent(), 0);
1252 assert_eq!(block.reference_count(), 0);
1253 assert_eq!(block.total_length(), 0);
1254 assert_eq!(block.inline_data().unwrap(), Vec::<u8>::new());
1255 assert_8_bytes!(container, 0, [0x01, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1256 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1257 }
1258
1259 #[fuchsia::test]
1260 fn test_inline_string_reference() {
1261 let (mut container, _storage) =
1262 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1263 let mut block = get_reserved(&mut container);
1264 block.set_order(0).unwrap();
1265 let mut block = block.become_string_reference();
1266
1267 assert_eq!(block.write_inline("ab".as_bytes()), 2);
1268 assert_eq!(block.reference_count(), 0);
1269 assert_eq!(block.total_length(), 2);
1270 assert_eq!(block.order(), 0);
1271 assert_eq!(*block.next_extent(), 0);
1272 assert_eq!(block.inline_data().unwrap(), "ab".as_bytes());
1273
1274 assert_eq!(block.write_inline("abcd".as_bytes()), 4);
1275 assert_eq!(block.reference_count(), 0);
1276 assert_eq!(block.total_length(), 4);
1277 assert_eq!(block.order(), 0);
1278 assert_eq!(*block.next_extent(), 0);
1279 assert_eq!(block.inline_data().unwrap(), "abcd".as_bytes());
1280
1281 assert_eq!(
1282 block.write_inline("abcdefghijklmnopqrstuvwxyz".as_bytes()),
1283 4 );
1285 assert_eq!(block.reference_count(), 0);
1286 assert_eq!(block.total_length(), 26);
1287 assert_eq!(block.order(), 0);
1288 assert_eq!(*block.next_extent(), 0);
1289 assert_eq!(block.inline_data().unwrap(), "abcd".as_bytes());
1290
1291 assert_eq!(block.write_inline("abcdef".as_bytes()), 4);
1292 assert_eq!(block.reference_count(), 0);
1293 assert_eq!(block.total_length(), 6);
1294 assert_eq!(block.order(), 0);
1295 assert_eq!(*block.next_extent(), 0);
1296 assert_eq!(block.inline_data().unwrap(), "abcd".as_bytes());
1297 }
1298
1299 #[fuchsia::test]
1300 fn test_string_reference_count() {
1301 let (mut container, _storage) =
1302 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1303 let mut block = get_reserved(&mut container);
1304 block.set_order(0).unwrap();
1305 let mut block = block.become_string_reference();
1306 assert_eq!(block.reference_count(), 0);
1307
1308 assert!(block.increment_ref_count().is_ok());
1309 assert_eq!(block.reference_count(), 1);
1310
1311 assert!(block.decrement_ref_count().is_ok());
1312 assert_eq!(block.reference_count(), 0);
1313
1314 assert!(block.decrement_ref_count().is_err());
1315 assert_eq!(block.reference_count(), 0);
1316
1317 HeaderFields::set_string_reference_count(&mut block, constants::MAX_REFERENCE_COUNT);
1318 assert_eq!(block.reference_count(), constants::MAX_REFERENCE_COUNT);
1319
1320 assert!(block.increment_ref_count().is_ok());
1321 assert_eq!(block.reference_count(), constants::MAX_REFERENCE_COUNT);
1322
1323 assert!(block.decrement_ref_count().is_ok());
1324 assert_eq!(block.reference_count(), constants::MAX_REFERENCE_COUNT);
1325 }
1326
1327 #[fuchsia::test]
1328 fn test_become_inspect_header() {
1329 let (mut container, _storage) =
1330 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1331 let block = get_reserved(&mut container)
1332 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1333 .unwrap();
1334 assert_eq!(block.block_type(), Some(BlockType::Header));
1335 assert_eq!(*block.index(), 0);
1336 assert_eq!(block.order(), constants::HEADER_ORDER);
1337 assert_eq!(block.magic_number(), constants::HEADER_MAGIC_NUMBER);
1338 assert_eq!(block.version(), constants::HEADER_VERSION_NUMBER);
1339 assert_eq!(block.vmo_size().unwrap().unwrap() as usize, constants::MIN_ORDER_SIZE * 2);
1340 assert_8_bytes!(container, 0, [0x01, 0x02, 0x02, 0x00, 0x49, 0x4e, 0x53, 0x50]);
1341 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1342 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1343 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1344 assert!(Block::parse_inspect_header(&container).is_some());
1345 assert!(Block::parse_blob_header(&container).is_none());
1346 }
1347
1348 #[fuchsia::test]
1349 fn test_become_blob_header() {
1350 let (mut container, _storage) =
1351 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1352 let block =
1353 get_reserved(&mut container).become_blob_header(constants::MIN_ORDER_SIZE * 2).unwrap();
1354 assert_eq!(block.block_type(), Some(BlockType::Header));
1355 assert_eq!(*block.index(), 0);
1356 assert_eq!(block.order(), constants::HEADER_ORDER);
1357 assert_eq!(block.magic_number(), constants::BLOB_HEADER_MAGIC_NUMBER);
1358 assert_eq!(block.version(), constants::HEADER_VERSION_NUMBER);
1359 assert_eq!(block.vmo_size().unwrap().unwrap() as usize, constants::MIN_ORDER_SIZE * 2);
1360 assert_8_bytes!(container, 0, [0x01, 0x02, 0x02, 0x00, 0x42, 0x4c, 0x4f, 0x42]);
1361 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1362 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1363 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1364 assert!(Block::parse_blob_header(&container).is_some());
1365 assert!(Block::parse_inspect_header(&container).is_none());
1366 }
1367
1368 #[fuchsia::test]
1369 fn test_header_without_size() {
1370 let (mut container, _storage) =
1371 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1372 let block = get_reserved(&mut container)
1373 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1374 .unwrap();
1375 assert_eq!(block.order(), constants::HEADER_ORDER);
1376 assert!(block.vmo_size().unwrap().is_some());
1377
1378 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1379
1380 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1382 assert!(block.set_order(0).is_ok());
1383 assert_eq!(block.vmo_size().unwrap(), None);
1384 assert!(block.set_vmo_size(123456789).is_ok());
1386 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1387 }
1388
1389 #[fuchsia::test]
1390 fn test_parse_header_short_container() {
1391 let short_buf = [0u8; constants::MIN_ORDER_SIZE - 1];
1392 assert!(Block::parse_inspect_header(&short_buf).is_none());
1393 assert!(Block::parse_blob_header(&short_buf).is_none());
1394 }
1395
1396 #[fuchsia::test]
1397 fn test_parse_header_wrong_block_type() {
1398 let (mut container, _storage) =
1399 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1400 let _ = get_reserved(&mut container);
1401 assert!(Block::parse_inspect_header(&container).is_none());
1402 assert!(Block::parse_blob_header(&container).is_none());
1403 }
1404
1405 #[fuchsia::test]
1406 fn test_parse_header_invalid_version() {
1407 let (mut container, _storage) =
1408 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1409 let _ = get_reserved(&mut container)
1410 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1411 .unwrap();
1412
1413 {
1416 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1417 HeaderFields::set_header_version(&mut block, constants::HEADER_VERSION_NUMBER - 1);
1418 }
1419 assert!(Block::parse_inspect_header(&container).is_some());
1420
1421 {
1423 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1424 HeaderFields::set_header_version(&mut block, constants::HEADER_VERSION_NUMBER + 1);
1425 }
1426 assert!(Block::parse_inspect_header(&container).is_none());
1427 }
1428
1429 #[fuchsia::test]
1430 fn test_parse_header_invalid_magic() {
1431 let (mut container, _storage) =
1432 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1433 let mut block = get_reserved(&mut container)
1434 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1435 .unwrap();
1436 block.set_magic(0x1234_5678);
1437 assert!(Block::parse_inspect_header(&container).is_none());
1438 assert!(Block::parse_blob_header(&container).is_none());
1439 }
1440
1441 #[fuchsia::test]
1442 fn test_freeze_thaw_header() {
1443 let (mut container, _storage) =
1444 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1445 let block = get_reserved(&mut container)
1446 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1447 .unwrap();
1448 assert_eq!(block.block_type(), Some(BlockType::Header));
1449 assert_eq!(*block.index(), 0);
1450 assert_eq!(block.order(), constants::HEADER_ORDER);
1451 assert_eq!(block.magic_number(), constants::HEADER_MAGIC_NUMBER);
1452 assert_eq!(block.version(), constants::HEADER_VERSION_NUMBER);
1453 assert!(!block.is_frozen());
1454 assert_eq!(block.unlocked_generation_count(), Some(0));
1455 assert_8_bytes!(container, 0, [0x01, 0x02, 0x02, 0x00, 0x49, 0x4e, 0x53, 0x50]);
1456 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1457 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1458 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1459
1460 let old = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER).freeze();
1461 let frozen_block = Block::parse_inspect_header(&container).unwrap();
1462 assert!(frozen_block.is_frozen());
1463 assert_eq!(frozen_block.unlocked_generation_count(), Some(constants::VMO_FROZEN));
1464 assert_8_bytes!(container, 8, [0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
1465 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1466 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1467 container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER).thaw(old);
1468 let thawed_block = Block::parse_inspect_header(&container).unwrap();
1469 assert!(!thawed_block.is_frozen());
1470 assert_eq!(thawed_block.unlocked_generation_count(), Some(0));
1471 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1472 assert_8_bytes!(container, 16, [0x020, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1473 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1474 }
1475
1476 #[fuchsia::test]
1477 fn test_unaligned_buffer_access() {
1478 #[repr(C, packed)]
1479 struct Unaligned(u8, [u8; 32]);
1480
1481 let (mut container, _storage) =
1482 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1483 let _ = get_reserved(&mut container)
1484 .become_inspect_header(constants::MIN_ORDER_SIZE * 2)
1485 .unwrap();
1486
1487 let mut unaligned = Unaligned(0, [0; 32]);
1488 assert_eq!(unaligned.0, 0);
1489 unaligned.1.copy_from_slice(container.get_slice_at(0, 32).unwrap());
1490
1491 let block = unaligned.1.block_at_unchecked::<Header>(BlockIndex::EMPTY);
1492 assert_eq!(block.magic_number(), constants::HEADER_MAGIC_NUMBER);
1493 assert_eq!(block.version(), constants::HEADER_VERSION_NUMBER);
1494 assert_eq!(block.generation_count(), 0);
1495 }
1496
1497 #[fuchsia::test]
1498 fn test_set_value_invalid_offset() {
1499 let mut buffer = [0u8; 16];
1500 assert_eq!(buffer.set_value(16, 42u32), Err(Error::InvalidOffset(16)));
1501 assert_eq!(buffer.set_value(14, 42u32), Err(Error::InvalidOffset(14)));
1502 assert_eq!(buffer.set_value(0, 42u32), Ok(()));
1503 assert_eq!(buffer.get_value::<u32>(0), Some(42));
1504 }
1505
1506 #[fuchsia::test]
1507 #[should_panic]
1508 fn test_cant_unlock_locked_header() {
1509 let (mut container, _storage) =
1510 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1511 let mut block = get_header(&mut container, constants::MIN_ORDER_SIZE * 2);
1512 block.unlock();
1514 }
1515
1516 #[fuchsia::test]
1517 #[should_panic]
1518 fn test_cant_lock_locked_header() {
1519 let (mut container, _storage) =
1520 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1521 let mut block = get_header(&mut container, constants::MIN_ORDER_SIZE * 2);
1522 block.lock();
1523 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1525 block.lock();
1526 }
1527
1528 #[fuchsia::test]
1529 #[should_panic]
1530 fn test_header_overflow() {
1531 let (mut container, _storage) =
1534 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1535 container.set_value(8, u64::MAX).unwrap();
1536 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1537 block.lock();
1538 }
1539
1540 #[fuchsia::test]
1541 fn test_lock_unlock_header() {
1542 let (mut container, _storage) =
1543 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1544 let mut block = get_header(&mut container, constants::MIN_ORDER_SIZE * 2);
1545 block.lock();
1546 assert!(block.is_locked());
1547 assert_eq!(block.unlocked_generation_count(), None);
1548 assert_eq!(block.generation_count(), 1);
1549 let header_bytes: [u8; 8] = [0x01, 0x02, 0x02, 0x00, 0x49, 0x4e, 0x53, 0x50];
1550 assert_8_bytes!(container, 0, header_bytes[..]);
1551 assert_8_bytes!(container, 8, [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1552 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1553 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1554 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1555 block.unlock();
1556 assert!(!block.is_locked());
1557 assert_eq!(block.unlocked_generation_count(), Some(2));
1558 assert_eq!(block.generation_count(), 2);
1559 assert_8_bytes!(container, 0, header_bytes[..]);
1560 assert_8_bytes!(container, 8, [0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1561 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1562 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1563
1564 container.set_value(8, u64::MAX).unwrap();
1566 let mut block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1567 block.unlock();
1568 assert_eq!(block.generation_count(), 0);
1569 assert_8_bytes!(container, 0, header_bytes[..]);
1570 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1571 assert_8_bytes!(container, 16, [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1572 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1573 }
1574
1575 #[fuchsia::test]
1576 fn test_header_vmo_size() {
1577 let (mut container, _storage) =
1578 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1579 let mut block = get_header(&mut container, constants::MIN_ORDER_SIZE * 2);
1580 assert!(block.set_vmo_size(constants::DEFAULT_VMO_SIZE_BYTES.try_into().unwrap()).is_ok());
1581 assert_8_bytes!(container, 0, [0x01, 0x02, 0x02, 0x00, 0x49, 0x4e, 0x53, 0x50]);
1582 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1583 assert_8_bytes!(container, 16, [0x00, 0x00, 0x4, 0x00, 0x00, 0x00, 0x00, 0x00]);
1584 assert_8_bytes!(container, 24, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1585 let block = container.block_at_unchecked_mut::<Header>(BlockIndex::HEADER);
1586 assert_eq!(block.vmo_size().unwrap().unwrap() as usize, constants::DEFAULT_VMO_SIZE_BYTES);
1587 }
1588
1589 #[fuchsia::test]
1590 fn test_become_tombstone() {
1591 let (mut container, _storage) =
1592 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1593 let mut block = get_reserved(&mut container).become_node(2.into(), 3.into());
1594 block.set_child_count(4);
1595 let block = block.become_tombstone();
1596 assert_eq!(block.block_type(), Some(BlockType::Tombstone));
1597 assert_eq!(block.child_count(), 4);
1598 assert_8_bytes!(container, 0, [0x01, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1599 assert_8_bytes!(container, 8, [0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1600 }
1601
1602 #[fuchsia::test]
1603 fn test_child_count() {
1604 let (mut container, _storage) =
1605 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1606 let _ = get_reserved(&mut container).become_node(2.into(), 3.into());
1607 assert_8_bytes!(container, 0, [0x01, 0x03, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1608 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1609 let mut block = container.block_at_unchecked_mut::<Node>(BlockIndex::EMPTY);
1610 block.set_child_count(4);
1611 assert_eq!(block.child_count(), 4);
1612 assert_8_bytes!(container, 0, [0x01, 0x03, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1613 assert_8_bytes!(container, 8, [0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1614 }
1615
1616 #[fuchsia::test]
1617 fn test_free() {
1618 let (mut container, _storage) =
1619 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1620 let mut block = Block::free(&mut container, BlockIndex::EMPTY, 1, 1.into()).unwrap();
1621 block.set_free_next_index(3.into());
1622 assert_eq!(*block.free_next_index(), 3);
1623 assert_8_bytes!(container, 0, [0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00]);
1624 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1625 }
1626
1627 #[fuchsia::test]
1628 fn test_extent() {
1629 let (mut container, _storage) =
1630 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1631 let block = get_reserved(&mut container).become_extent(3.into());
1632 assert_eq!(block.block_type(), Some(BlockType::Extent));
1633 assert_eq!(*block.next_extent(), 3);
1634 assert_8_bytes!(container, 0, [0x01, 0x08, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00]);
1635 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1636
1637 let mut block = container.block_at_unchecked_mut::<Extent>(BlockIndex::EMPTY);
1638 assert_eq!(block.set_contents("test-rust-inspect".as_bytes()), 17);
1639 assert_eq!(
1640 String::from_utf8(block.contents().unwrap().to_vec()).unwrap(),
1641 "test-rust-inspect\0\0\0\0\0\0\0"
1642 );
1643 let slice = container.get_slice_at(8, 17).unwrap();
1644 assert_eq!(slice, "test-rust-inspect".as_bytes());
1645 let slice = container.get_slice_at(25, 7).unwrap();
1646 assert_eq!(slice, &[0, 0, 0, 0, 0, 0, 0]);
1647
1648 let mut block = container.block_at_unchecked_mut::<Extent>(BlockIndex::EMPTY);
1649 block.set_next_index(4.into());
1650 assert_eq!(*block.next_extent(), 4);
1651 }
1652
1653 #[fuchsia::test]
1654 fn test_double_value() {
1655 let (mut container, _storage) =
1656 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1657 let block = get_reserved(&mut container).become_double_value(1.0, 2.into(), 3.into());
1658 assert_eq!(block.block_type(), Some(BlockType::DoubleValue));
1659 assert_eq!(*block.name_index(), 2);
1660 assert_eq!(*block.parent_index(), 3);
1661 assert_eq!(block.value(), 1.0);
1662 assert_8_bytes!(container, 0, [0x01, 0x06, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1663 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f]);
1664
1665 let mut block = container.block_at_unchecked_mut::<Double>(BlockIndex::EMPTY);
1666 block.set(5.0);
1667 assert_eq!(block.value(), 5.0);
1668 assert_8_bytes!(container, 0, [0x01, 0x06, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1669 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40]);
1670 }
1671
1672 #[fuchsia::test]
1673 fn test_int_value() {
1674 let (mut container, _storage) =
1675 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1676 let block = get_reserved(&mut container).become_int_value(1, 2.into(), 3.into());
1677 assert_eq!(block.block_type(), Some(BlockType::IntValue));
1678 assert_eq!(*block.name_index(), 2);
1679 assert_eq!(*block.parent_index(), 3);
1680 assert_eq!(block.value(), 1);
1681 assert_8_bytes!(container, 0, [0x1, 0x04, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1682 assert_8_bytes!(container, 8, [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1683
1684 let mut block = container.block_at_unchecked_mut::<Int>(BlockIndex::EMPTY);
1685 block.set(-5);
1686 assert_eq!(block.value(), -5);
1687 assert_8_bytes!(container, 0, [0x1, 0x04, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1688 assert_8_bytes!(container, 8, [0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
1689 }
1690
1691 #[fuchsia::test]
1692 fn test_uint_value() {
1693 let (mut container, _storage) =
1694 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1695 let block = get_reserved(&mut container).become_uint_value(1, 2.into(), 3.into());
1696 assert_eq!(block.block_type(), Some(BlockType::UintValue));
1697 assert_eq!(*block.name_index(), 2);
1698 assert_eq!(*block.parent_index(), 3);
1699 assert_eq!(block.value(), 1);
1700 assert_8_bytes!(container, 0, [0x01, 0x05, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1701 assert_8_bytes!(container, 8, [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1702
1703 let mut block = container.block_at_unchecked_mut::<Uint>(BlockIndex::EMPTY);
1704 block.set(5);
1705 assert_eq!(block.value(), 5);
1706 assert_8_bytes!(container, 0, [0x01, 0x05, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1707 assert_8_bytes!(container, 8, [0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1708 }
1709
1710 #[fuchsia::test]
1711 fn test_bool_value() {
1712 let (mut container, _storage) =
1713 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1714 let block = get_reserved(&mut container).become_bool_value(false, 2.into(), 3.into());
1715 assert_eq!(block.block_type(), Some(BlockType::BoolValue));
1716 assert_eq!(*block.name_index(), 2);
1717 assert_eq!(*block.parent_index(), 3);
1718 assert!(!block.value());
1719 assert_8_bytes!(container, 0, [0x01, 0x0D, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1720 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1721
1722 let mut block = container.block_at_unchecked_mut::<Bool>(BlockIndex::EMPTY);
1723 block.set(true);
1724 assert!(block.value());
1725 assert_8_bytes!(container, 0, [0x01, 0x0D, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1726 assert_8_bytes!(container, 8, [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1727 }
1728
1729 #[fuchsia::test]
1730 fn test_become_node() {
1731 let (mut container, _storage) =
1732 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1733 let block = get_reserved(&mut container).become_node(2.into(), 3.into());
1734 assert_eq!(block.block_type(), Some(BlockType::NodeValue));
1735 assert_eq!(*block.name_index(), 2);
1736 assert_eq!(*block.parent_index(), 3);
1737 assert_8_bytes!(container, 0, [0x01, 0x03, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1738 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1739 }
1740
1741 #[fuchsia::test]
1742 fn test_property() {
1743 let (mut container, _storage) =
1744 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1745 let block =
1746 get_reserved(&mut container).become_property(2.into(), 3.into(), PropertyFormat::Bytes);
1747 assert_eq!(block.block_type(), Some(BlockType::BufferValue));
1748 assert_eq!(*block.name_index(), 2);
1749 assert_eq!(*block.parent_index(), 3);
1750 assert_eq!(block.format(), Some(PropertyFormat::Bytes));
1751 assert_8_bytes!(container, 0, [0x01, 0x07, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1752 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10]);
1753
1754 let (mut bad_container, _storage) =
1755 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1756 let mut bad_format_bytes = [0u8; constants::MIN_ORDER_SIZE];
1757 bad_format_bytes[15] = 0x30;
1758 bad_container.copy_from_slice(&bad_format_bytes);
1759 let bad_block = Block::<_, Buffer>::new(&bad_container, BlockIndex::EMPTY);
1760 assert_eq!(bad_block.format(), None);
1761
1762 let mut block = container.block_at_unchecked_mut::<Buffer>(BlockIndex::EMPTY);
1763 block.set_extent_index(4.into());
1764 assert_eq!(*block.extent_index(), 4);
1765 assert_8_bytes!(container, 0, [0x01, 0x07, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1766 assert_8_bytes!(container, 8, [0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x10]);
1767
1768 let mut block = container.block_at_unchecked_mut::<Buffer>(BlockIndex::EMPTY);
1769 block.set_total_length(10);
1770 assert_eq!(block.total_length(), 10);
1771 assert_8_bytes!(container, 0, [0x01, 0x07, 0x03, 0x00, 0x00, 0x02, 0x00, 0x00]);
1772 assert_8_bytes!(container, 8, [0x0a, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x10]);
1773 }
1774
1775 #[fuchsia::test]
1776 fn test_name() {
1777 let (mut container, _storage) =
1778 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1779 let block = get_reserved(&mut container).become_name("test-rust-inspect");
1780 assert_eq!(block.block_type(), Some(BlockType::Name));
1781 assert_eq!(block.length(), 17);
1782 assert_eq!(block.contents().unwrap(), "test-rust-inspect");
1783 assert_8_bytes!(container, 0, [0x01, 0x09, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00]);
1784 let slice = container.get_slice_at(8, 17).unwrap();
1785 assert_eq!(slice, "test-rust-inspect".as_bytes());
1786 let slice = container.get_slice_at(25, 7).unwrap();
1787 assert_eq!(slice, [0, 0, 0, 0, 0, 0, 0]);
1788
1789 container.set_value::<u8>(24, 0xff).unwrap();
1790 let bad_block = Block::<_, Name>::new(&container, BlockIndex::EMPTY);
1791 assert_eq!(bad_block.length(), 17); assert!(bad_block.contents().is_err()); let (mut container, _storage) =
1797 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1798 let block = get_reserved(&mut container).become_name("abcdefghijklmnopqrstuvwxyz");
1799 assert_eq!(block.contents().unwrap(), "abcdefghijklmnopqrstuvwx");
1800
1801 let (mut container, _storage) =
1802 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1803 let block = get_reserved(&mut container).become_name("😀abcdefghijklmnopqrstuvwxyz");
1804 assert_eq!(block.contents().unwrap(), "😀abcdefghijklmnopqrst");
1805
1806 let (mut container, _storage) =
1807 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1808 let block = get_reserved(&mut container).become_name("abcdefghijklmnopqrstu😀");
1809 assert_eq!(block.contents().unwrap(), "abcdefghijklmnopqrstu");
1810 let byte = container.get_value::<u8>(31).unwrap();
1811 assert_eq!(byte, 0);
1812
1813 let (mut container, _storage) =
1814 Container::read_and_write(constants::MIN_ORDER_SIZE * 2).unwrap();
1815 let block = get_reserved(&mut container).become_name("🦀🦀🦀🦀🦀🦀🦀🦀");
1816 assert_eq!(block.contents().unwrap(), "🦀🦀🦀🦀🦀🦀");
1817 }
1818
1819 #[fuchsia::test]
1820 fn test_invalid_type_for_array() {
1821 let (mut container, _storage) = Container::read_and_write(2048).unwrap();
1822 container.get_slice_mut_at(24, 2048 - 24).unwrap().fill(14);
1823
1824 fn become_array<S: ArraySlotKind>(
1825 container: &mut Container,
1826 format: ArrayFormat,
1827 ) -> Result<Block<&mut Container, Array<S>>, Error> {
1828 get_reserved_of_order(container, 4).become_array_value::<S>(
1829 4,
1830 format,
1831 BlockIndex::EMPTY,
1832 BlockIndex::EMPTY,
1833 )
1834 }
1835
1836 assert!(become_array::<Int>(&mut container, ArrayFormat::Default).is_ok());
1837 assert!(become_array::<Uint>(&mut container, ArrayFormat::Default).is_ok());
1838 assert!(become_array::<Double>(&mut container, ArrayFormat::Default).is_ok());
1839 assert!(become_array::<StringRef>(&mut container, ArrayFormat::Default).is_ok());
1840
1841 for format in [ArrayFormat::LinearHistogram, ArrayFormat::ExponentialHistogram] {
1842 assert!(become_array::<Int>(&mut container, format).is_ok());
1843 assert!(become_array::<Uint>(&mut container, format).is_ok());
1844 assert!(become_array::<Double>(&mut container, format).is_ok());
1845 assert!(become_array::<StringRef>(&mut container, format).is_err());
1846 }
1847 }
1848
1849 #[fuchsia::test]
1855 fn test_string_arrays() {
1856 let (mut container, _storage) = Container::read_and_write(2048).unwrap();
1857 container.get_slice_mut_at(48, 2048 - 48).unwrap().fill(14);
1858
1859 let parent_index = BlockIndex::new(0);
1860 let name_index = BlockIndex::new(1);
1861 let mut block = get_reserved(&mut container)
1862 .become_array_value::<StringRef>(4, ArrayFormat::Default, name_index, parent_index)
1863 .unwrap();
1864
1865 for i in 0..4 {
1866 block.set_string_slot(i, ((i + 4) as u32).into());
1867 }
1868
1869 for i in 0..4 {
1870 let read_index = block.get_string_index_at(i).unwrap();
1871 assert_eq!(*read_index, (i + 4) as u32);
1872 }
1873
1874 assert_8_bytes!(
1875 container,
1876 0,
1877 [
1878 0x01, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00
1881 ]
1882 );
1883 assert_8_bytes!(container, 8, [0x0E, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1884 for i in 0..4 {
1885 let slice = container.get_slice_at(16 + (i * 4), 4).unwrap();
1886 assert_eq!(slice, [(i as u8 + 4), 0x00, 0x00, 0x00]);
1887 }
1888 }
1889
1890 #[fuchsia::test]
1891 fn become_array() {
1892 let (mut container, _storage) = Container::read_and_write(128).unwrap();
1894 container.get_slice_mut_at(16, 128 - 16).unwrap().fill(1);
1895
1896 let _ = Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
1897 .unwrap()
1898 .become_reserved()
1899 .become_array_value::<Int>(
1900 14,
1901 ArrayFormat::Default,
1902 BlockIndex::EMPTY,
1903 BlockIndex::EMPTY,
1904 )
1905 .unwrap();
1906 let slice = container.get_slice_at(16, 128 - 16).unwrap();
1907 slice
1908 .iter()
1909 .enumerate()
1910 .for_each(|(index, i)| assert_eq!(*i, 0, "failed: byte = {} at index {}", *i, index));
1911
1912 container.get_slice_mut_at(16, 128 - 16).unwrap().fill(1);
1913 let _ = Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
1914 .unwrap()
1915 .become_reserved()
1916 .become_array_value::<Int>(
1917 14,
1918 ArrayFormat::LinearHistogram,
1919 BlockIndex::EMPTY,
1920 BlockIndex::EMPTY,
1921 )
1922 .unwrap();
1923 let slice = container.get_slice_at(16, 128 - 16).unwrap();
1924 slice
1925 .iter()
1926 .enumerate()
1927 .for_each(|(index, i)| assert_eq!(*i, 0, "failed: byte = {} at index {}", *i, index));
1928
1929 container.get_slice_mut_at(16, 128 - 16).unwrap().fill(1);
1930 let _ = Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
1931 .unwrap()
1932 .become_reserved()
1933 .become_array_value::<Int>(
1934 14,
1935 ArrayFormat::ExponentialHistogram,
1936 BlockIndex::EMPTY,
1937 BlockIndex::EMPTY,
1938 )
1939 .unwrap();
1940 let slice = container.get_slice_at(16, 128 - 16).unwrap();
1941 slice
1942 .iter()
1943 .enumerate()
1944 .for_each(|(index, i)| assert_eq!(*i, 0, "failed: byte = {} at index {}", *i, index));
1945
1946 container.get_slice_mut_at(16, 128 - 16).unwrap().fill(1);
1947 let _ = Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
1948 .unwrap()
1949 .become_reserved()
1950 .become_array_value::<StringRef>(
1951 28,
1952 ArrayFormat::Default,
1953 BlockIndex::EMPTY,
1954 BlockIndex::EMPTY,
1955 )
1956 .unwrap();
1957 let slice = container.get_slice_at(16, 128 - 16).unwrap();
1958 slice
1959 .iter()
1960 .enumerate()
1961 .for_each(|(index, i)| assert_eq!(*i, 0, "failed: byte = {} at index {}", *i, index));
1962 }
1963
1964 #[fuchsia::test]
1965 fn uint_array_value() {
1966 let (mut container, _storage) =
1967 Container::read_and_write(constants::MIN_ORDER_SIZE * 4).unwrap();
1968 let mut block = Block::free(&mut container, BlockIndex::EMPTY, 2, BlockIndex::EMPTY)
1969 .unwrap()
1970 .become_reserved()
1971 .become_array_value::<Uint>(4, ArrayFormat::LinearHistogram, 3.into(), 2.into())
1972 .unwrap();
1973
1974 assert_eq!(block.block_type(), Some(BlockType::ArrayValue));
1975 assert_eq!(*block.parent_index(), 2);
1976 assert_eq!(*block.name_index(), 3);
1977 assert_eq!(block.format(), Some(ArrayFormat::LinearHistogram));
1978 assert_eq!(block.slots(), 4);
1979 assert_eq!(block.entry_type(), Some(BlockType::UintValue));
1980
1981 for i in 0..4 {
1982 block.set(i, (i as u64 + 1) * 5);
1983 }
1984 block.set(4, 3);
1985 block.set(7, 5);
1986
1987 assert_8_bytes!(container, 0, [0x02, 0x0b, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00]);
1988 assert_8_bytes!(container, 8, [0x15, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
1989 for i in 0..4 {
1990 assert_8_bytes!(
1991 container,
1992 8 * (i + 2),
1993 [(i as u8 + 1) * 5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
1994 );
1995 }
1996
1997 let (mut bad_container, _storage) =
1998 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
1999 let mut bad_bytes = [0u8; constants::MIN_ORDER_SIZE];
2000 container.copy_bytes(&mut bad_bytes[..]);
2001 bad_bytes[8] = 0x12; bad_container.copy_from_slice(&bad_bytes);
2003 let bad_block = Block::<_, Array<Uint>>::new(&bad_container, BlockIndex::EMPTY);
2004 assert_eq!(bad_block.format(), Some(ArrayFormat::LinearHistogram));
2005 assert_eq!(bad_block.entry_type(), None);
2007
2008 bad_bytes[8] = 0xef; bad_container.copy_from_slice(&bad_bytes);
2010 let bad_block = Block::<_, Array<Uint>>::new(&bad_container, BlockIndex::EMPTY);
2011 assert_eq!(bad_block.format(), None);
2012 assert_eq!(bad_block.entry_type(), None);
2013
2014 let block = container.block_at_unchecked::<Array<Uint>>(BlockIndex::EMPTY);
2015 for i in 0..4 {
2016 assert_eq!(block.get(i), Some((i as u64 + 1) * 5));
2017 }
2018 assert_eq!(block.get(4), None);
2019 }
2020
2021 #[fuchsia::test]
2022 fn array_slots_bigger_than_block_order() {
2023 let (mut container, _storage) =
2024 Container::read_and_write(constants::MAX_ORDER_SIZE).unwrap();
2025 assert!(
2028 Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
2029 .unwrap()
2030 .become_reserved()
2031 .become_array_value::<Int>(257, ArrayFormat::Default, 1.into(), 2.into())
2032 .is_err()
2033 );
2034 assert!(
2035 Block::free(&mut container, BlockIndex::EMPTY, 7, BlockIndex::EMPTY)
2036 .unwrap()
2037 .become_reserved()
2038 .become_array_value::<Int>(254, ArrayFormat::Default, 1.into(), 2.into())
2039 .is_ok()
2040 );
2041
2042 assert!(
2045 Block::free(&mut container, BlockIndex::EMPTY, 2, BlockIndex::EMPTY)
2046 .unwrap()
2047 .become_reserved()
2048 .become_array_value::<Int>(8, ArrayFormat::Default, 1.into(), 2.into())
2049 .is_err()
2050 );
2051 assert!(
2052 Block::free(&mut container, BlockIndex::EMPTY, 2, BlockIndex::EMPTY)
2053 .unwrap()
2054 .become_reserved()
2055 .become_array_value::<Int>(6, ArrayFormat::Default, 1.into(), 2.into())
2056 .is_ok()
2057 );
2058 }
2059
2060 #[fuchsia::test]
2061 fn array_clear() {
2062 let (mut container, _storage) =
2063 Container::read_and_write(constants::MIN_ORDER_SIZE * 4).unwrap();
2064
2065 let sample = [0xff, 0xff, 0xff];
2067 container.copy_from_slice_at(48, &sample);
2068
2069 let mut block = Block::free(&mut container, BlockIndex::EMPTY, 2, BlockIndex::EMPTY)
2070 .unwrap()
2071 .become_reserved()
2072 .become_array_value::<Uint>(4, ArrayFormat::LinearHistogram, 3.into(), 2.into())
2073 .unwrap();
2074
2075 for i in 0..4 {
2076 block.set(i, (i + 1) as u64);
2077 }
2078
2079 block.clear(1);
2080
2081 assert_eq!(1, block.get(0).expect("get uint 0"));
2082 assert_8_bytes!(container, 16, [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
2083
2084 for i in 1..4 {
2085 let block = container.block_at_unchecked::<Array<Uint>>(BlockIndex::EMPTY);
2086 assert_eq!(0, block.get(i).expect("get uint"));
2087 assert_8_bytes!(
2088 container,
2089 16 + (i * 8),
2090 [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
2091 );
2092 }
2093
2094 let slice = container.get_slice_at(48, 3).unwrap();
2096 assert_eq!(slice, &sample[..]);
2097 }
2098
2099 #[fuchsia::test]
2100 fn become_link() {
2101 let (mut container, _storage) =
2102 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
2103 let block = get_reserved(&mut container).become_link(
2104 BlockIndex::new(1),
2105 BlockIndex::new(2),
2106 BlockIndex::new(3),
2107 LinkNodeDisposition::Inline,
2108 );
2109 assert_eq!(*block.name_index(), 1);
2110 assert_eq!(*block.parent_index(), 2);
2111 assert_eq!(*block.content_index(), 3);
2112 assert_eq!(block.block_type(), Some(BlockType::LinkValue));
2113 assert_eq!(block.link_node_disposition(), Some(LinkNodeDisposition::Inline));
2114 assert_8_bytes!(container, 0, [0x01, 0x0c, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00]);
2115 assert_8_bytes!(container, 8, [0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10]);
2116
2117 let block = get_reserved(&mut container).become_link(
2118 BlockIndex::new(1),
2119 BlockIndex::new(2),
2120 BlockIndex::new(3),
2121 LinkNodeDisposition::Blob,
2122 );
2123 assert_eq!(block.link_node_disposition(), Some(LinkNodeDisposition::Blob));
2124 assert_8_bytes!(container, 8, [0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20]);
2125 }
2126
2127 #[test]
2128 fn array_capacity_numeric() {
2129 assert_eq!(2, max_array_capacity::<Int>(1));
2130 assert_eq!(2 + 4, max_array_capacity::<Int>(2));
2131 assert_eq!(2 + 4 + 8, max_array_capacity::<Int>(3));
2132 assert_eq!(2 + 4 + 8 + 16, max_array_capacity::<Int>(4));
2133 assert_eq!(2 + 4 + 8 + 16 + 32, max_array_capacity::<Int>(5));
2134 assert_eq!(2 + 4 + 8 + 16 + 32 + 64, max_array_capacity::<Int>(6));
2135 assert_eq!(2 + 4 + 8 + 16 + 32 + 64 + 128, max_array_capacity::<Int>(7),);
2136 }
2137
2138 #[test]
2139 fn array_capacity_string_reference() {
2140 assert_eq!(4, max_array_capacity::<StringRef>(1));
2141 assert_eq!(4 + 8, max_array_capacity::<StringRef>(2));
2142 assert_eq!(4 + 8 + 16, max_array_capacity::<StringRef>(3));
2143 assert_eq!(4 + 8 + 16 + 32, max_array_capacity::<StringRef>(4));
2144 assert_eq!(4 + 8 + 16 + 32 + 64, max_array_capacity::<StringRef>(5));
2145 assert_eq!(4 + 8 + 16 + 32 + 64 + 128, max_array_capacity::<StringRef>(6));
2146 assert_eq!(4 + 8 + 16 + 32 + 64 + 128 + 256, max_array_capacity::<StringRef>(7));
2147 }
2148
2149 #[fuchsia::test]
2150 fn set_parent_and_name() {
2151 let (mut container, _storage) =
2152 Container::read_and_write(constants::MIN_ORDER_SIZE).unwrap();
2153 let mut block =
2154 get_reserved(&mut container).become_node(BlockIndex::new(1), BlockIndex::new(2));
2155 assert_eq!(*block.name_index(), 1);
2156 assert_eq!(*block.parent_index(), 2);
2157 block.set_name(BlockIndex::new(3));
2158 block.set_parent(BlockIndex::new(4));
2159 assert_eq!(*block.name_index(), 3);
2160 assert_eq!(*block.parent_index(), 4);
2161 }
2162
2163 fn get_header(container: &mut Container, size: usize) -> Block<&mut Container, Header> {
2164 get_reserved(container).become_inspect_header(size).unwrap()
2165 }
2166
2167 fn get_reserved(container: &mut Container) -> Block<&mut Container, Reserved> {
2168 get_reserved_of_order(container, 1)
2169 }
2170
2171 fn get_reserved_of_order(
2172 container: &mut Container,
2173 order: u8,
2174 ) -> Block<&mut Container, Reserved> {
2175 let block = Block::free(container, BlockIndex::EMPTY, order, BlockIndex::new(0)).unwrap();
2176 block.become_reserved()
2177 }
2178}