1 //! The virtual memory representation of the MIR interpreter.
4 read_target_uint
, write_target_uint
, AllocId
, InterpResult
, Pointer
, Scalar
, ScalarMaybeUndef
,
7 use crate::ty
::layout
::{Align, Size}
;
9 use rustc_ast
::ast
::Mutability
;
10 use rustc_data_structures
::sorted_map
::SortedMap
;
11 use rustc_target
::abi
::HasDataLayout
;
14 use std
::ops
::{Deref, DerefMut, Range}
;
16 // NOTE: When adding new fields, make sure to adjust the `Snapshot` impl in
17 // `src/librustc_mir/interpret/snapshot.rs`.
30 pub struct Allocation
<Tag
= (), Extra
= ()> {
31 /// The actual bytes of the allocation.
32 /// Note that the bytes of a pointer represent the offset of the pointer.
34 /// Maps from byte addresses to extra data for each pointer.
35 /// Only the first byte of a pointer is inserted into the map; i.e.,
36 /// every entry in this map applies to `pointer_size` consecutive bytes starting
37 /// at the given offset.
38 relocations
: Relocations
<Tag
>,
39 /// Denotes which part of this allocation is initialized.
40 undef_mask
: UndefMask
,
41 /// The size of the allocation. Currently, must always equal `bytes.len()`.
43 /// The alignment of the allocation to detect unaligned reads.
45 /// `true` if the allocation is mutable.
46 /// Also used by codegen to determine if a static should be put into mutable memory,
47 /// which happens for `static mut` and `static` with interior mutability.
48 pub mutability
: Mutability
,
49 /// Extra state for the machine.
53 pub trait AllocationExtra
<Tag
>: ::std
::fmt
::Debug
+ Clone
{
54 // There is no constructor in here because the constructor's type depends
55 // on `MemoryKind`, and making things sufficiently generic leads to painful
58 /// Hook for performing extra checks on a memory read access.
60 /// Takes read-only access to the allocation so we can keep all the memory read
61 /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
65 _alloc
: &Allocation
<Tag
, Self>,
68 ) -> InterpResult
<'tcx
> {
72 /// Hook for performing extra checks on a memory write access.
75 _alloc
: &mut Allocation
<Tag
, Self>,
78 ) -> InterpResult
<'tcx
> {
82 /// Hook for performing extra checks on a memory deallocation.
83 /// `size` will be the size of the allocation.
85 fn memory_deallocated(
86 _alloc
: &mut Allocation
<Tag
, Self>,
89 ) -> InterpResult
<'tcx
> {
94 // For `Tag = ()` and no extra state, we have a trivial implementation.
95 impl AllocationExtra
<()> for () {}
97 // The constructors are all without extra; the extra gets added by a machine hook later.
98 impl<Tag
> Allocation
<Tag
> {
99 /// Creates a read-only allocation initialized by the given bytes
100 pub fn from_bytes
<'a
>(slice
: impl Into
<Cow
<'a
, [u8]>>, align
: Align
) -> Self {
101 let bytes
= slice
.into().into_owned();
102 let size
= Size
::from_bytes(bytes
.len() as u64);
105 relocations
: Relocations
::new(),
106 undef_mask
: UndefMask
::new(size
, true),
109 mutability
: Mutability
::Not
,
114 pub fn from_byte_aligned_bytes
<'a
>(slice
: impl Into
<Cow
<'a
, [u8]>>) -> Self {
115 Allocation
::from_bytes(slice
, Align
::from_bytes(1).unwrap())
118 pub fn undef(size
: Size
, align
: Align
) -> Self {
119 assert_eq
!(size
.bytes() as usize as u64, size
.bytes());
121 bytes
: vec
![0; size
.bytes() as usize],
122 relocations
: Relocations
::new(),
123 undef_mask
: UndefMask
::new(size
, false),
126 mutability
: Mutability
::Mut
,
132 impl Allocation
<(), ()> {
133 /// Add Tag and Extra fields
134 pub fn with_tags_and_extra
<T
, E
>(
136 mut tagger
: impl FnMut(AllocId
) -> T
,
138 ) -> Allocation
<T
, E
> {
142 relocations
: Relocations
::from_presorted(
145 // The allocations in the relocations (pointers stored *inside* this allocation)
146 // all get the base pointer tag.
147 .map(|&(offset
, ((), alloc
))| {
148 let tag
= tagger(alloc
);
149 (offset
, (tag
, alloc
))
153 undef_mask
: self.undef_mask
,
155 mutability
: self.mutability
,
161 /// Raw accessors. Provide access to otherwise private bytes.
162 impl<Tag
, Extra
> Allocation
<Tag
, Extra
> {
163 pub fn len(&self) -> usize {
164 self.size
.bytes() as usize
167 /// Looks at a slice which may describe undefined bytes or describe a relocation. This differs
168 /// from `get_bytes_with_undef_and_ptr` in that it does no relocation checks (even on the
169 /// edges) at all. It further ignores `AllocationExtra` callbacks.
170 /// This must not be used for reads affecting the interpreter execution.
171 pub fn inspect_with_undef_and_ptr_outside_interpreter(&self, range
: Range
<usize>) -> &[u8] {
175 /// Returns the undef mask.
176 pub fn undef_mask(&self) -> &UndefMask
{
180 /// Returns the relocation list.
181 pub fn relocations(&self) -> &Relocations
<Tag
> {
186 impl<'tcx
> rustc_serialize
::UseSpecializedDecodable
for &'tcx Allocation {}
189 impl<'tcx
, Tag
: Copy
, Extra
: AllocationExtra
<Tag
>> Allocation
<Tag
, Extra
> {
190 /// Just a small local helper function to avoid a bit of code repetition.
191 /// Returns the range of this allocation that was meant.
193 fn check_bounds(&self, offset
: Size
, size
: Size
) -> Range
<usize> {
194 let end
= offset
+ size
; // This does overflow checking.
196 end
.bytes() as usize as u64,
198 "cannot handle this access on this host architecture"
200 let end
= end
.bytes() as usize;
203 "Out-of-bounds access at offset {}, size {} in allocation of size {}",
208 (offset
.bytes() as usize)..end
211 /// The last argument controls whether we error out when there are undefined
212 /// or pointer bytes. You should never call this, call `get_bytes` or
213 /// `get_bytes_with_undef_and_ptr` instead,
215 /// This function also guarantees that the resulting pointer will remain stable
216 /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
219 /// It is the caller's responsibility to check bounds and alignment beforehand.
220 fn get_bytes_internal(
222 cx
: &impl HasDataLayout
,
225 check_defined_and_ptr
: bool
,
226 ) -> InterpResult
<'tcx
, &[u8]> {
227 let range
= self.check_bounds(ptr
.offset
, size
);
229 if check_defined_and_ptr
{
230 self.check_defined(ptr
, size
)?
;
231 self.check_relocations(cx
, ptr
, size
)?
;
233 // We still don't want relocations on the *edges*.
234 self.check_relocation_edges(cx
, ptr
, size
)?
;
237 AllocationExtra
::memory_read(self, ptr
, size
)?
;
239 Ok(&self.bytes
[range
])
242 /// Checks that these bytes are initialized and not pointer bytes, and then return them
245 /// It is the caller's responsibility to check bounds and alignment beforehand.
246 /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
247 /// on `InterpCx` instead.
251 cx
: &impl HasDataLayout
,
254 ) -> InterpResult
<'tcx
, &[u8]> {
255 self.get_bytes_internal(cx
, ptr
, size
, true)
258 /// It is the caller's responsibility to handle undefined and pointer bytes.
259 /// However, this still checks that there are no relocations on the *edges*.
261 /// It is the caller's responsibility to check bounds and alignment beforehand.
263 pub fn get_bytes_with_undef_and_ptr(
265 cx
: &impl HasDataLayout
,
268 ) -> InterpResult
<'tcx
, &[u8]> {
269 self.get_bytes_internal(cx
, ptr
, size
, false)
272 /// Just calling this already marks everything as defined and removes relocations,
273 /// so be sure to actually put data there!
275 /// It is the caller's responsibility to check bounds and alignment beforehand.
276 /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods
277 /// on `InterpCx` instead.
278 pub fn get_bytes_mut(
280 cx
: &impl HasDataLayout
,
283 ) -> InterpResult
<'tcx
, &mut [u8]> {
284 let range
= self.check_bounds(ptr
.offset
, size
);
286 self.mark_definedness(ptr
, size
, true);
287 self.clear_relocations(cx
, ptr
, size
)?
;
289 AllocationExtra
::memory_written(self, ptr
, size
)?
;
291 Ok(&mut self.bytes
[range
])
295 /// Reading and writing.
296 impl<'tcx
, Tag
: Copy
, Extra
: AllocationExtra
<Tag
>> Allocation
<Tag
, Extra
> {
297 /// Reads bytes until a `0` is encountered. Will error if the end of the allocation is reached
298 /// before a `0` is found.
300 /// Most likely, you want to call `Memory::read_c_str` instead of this method.
303 cx
: &impl HasDataLayout
,
305 ) -> InterpResult
<'tcx
, &[u8]> {
306 assert_eq
!(ptr
.offset
.bytes() as usize as u64, ptr
.offset
.bytes());
307 let offset
= ptr
.offset
.bytes() as usize;
308 Ok(match self.bytes
[offset
..].iter().position(|&c
| c
== 0) {
310 let size_with_null
= Size
::from_bytes((size
+ 1) as u64);
311 // Go through `get_bytes` for checks and AllocationExtra hooks.
312 // We read the null, so we include it in the request, but we want it removed
313 // from the result, so we do subslicing.
314 &self.get_bytes(cx
, ptr
, size_with_null
)?
[..size
]
316 // This includes the case where `offset` is out-of-bounds to begin with.
317 None
=> throw_unsup
!(UnterminatedCString(ptr
.erase_tag())),
321 /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a
322 /// relocation. If `allow_ptr_and_undef` is `false`, also enforces that the memory in the
323 /// given range contains neither relocations nor undef bytes.
326 cx
: &impl HasDataLayout
,
329 allow_ptr_and_undef
: bool
,
330 ) -> InterpResult
<'tcx
> {
331 // Check bounds and relocations on the edges.
332 self.get_bytes_with_undef_and_ptr(cx
, ptr
, size
)?
;
333 // Check undef and ptr.
334 if !allow_ptr_and_undef
{
335 self.check_defined(ptr
, size
)?
;
336 self.check_relocations(cx
, ptr
, size
)?
;
341 /// Writes `src` to the memory starting at `ptr.offset`.
343 /// It is the caller's responsibility to check bounds and alignment beforehand.
344 /// Most likely, you want to call `Memory::write_bytes` instead of this method.
347 cx
: &impl HasDataLayout
,
349 src
: impl IntoIterator
<Item
= u8>,
350 ) -> InterpResult
<'tcx
> {
351 let mut src
= src
.into_iter();
352 let (lower
, upper
) = src
.size_hint();
353 let len
= upper
.expect("can only write bounded iterators");
354 assert_eq
!(lower
, len
, "can only write iterators with a precise length");
355 let bytes
= self.get_bytes_mut(cx
, ptr
, Size
::from_bytes(len
as u64))?
;
356 // `zip` would stop when the first iterator ends; we want to definitely
357 // cover all of `bytes`.
359 *dest
= src
.next().expect("iterator was shorter than it said it would be");
361 src
.next().expect_none("iterator was longer than it said it would be");
365 /// Reads a *non-ZST* scalar.
367 /// ZSTs can't be read for two reasons:
368 /// * byte-order cannot work with zero-element buffers;
369 /// * in order to obtain a `Pointer`, we need to check for ZSTness anyway due to integer
370 /// pointers being valid for ZSTs.
372 /// It is the caller's responsibility to check bounds and alignment beforehand.
373 /// Most likely, you want to call `InterpCx::read_scalar` instead of this method.
376 cx
: &impl HasDataLayout
,
379 ) -> InterpResult
<'tcx
, ScalarMaybeUndef
<Tag
>> {
380 // `get_bytes_unchecked` tests relocation edges.
381 let bytes
= self.get_bytes_with_undef_and_ptr(cx
, ptr
, size
)?
;
382 // Undef check happens *after* we established that the alignment is correct.
383 // We must not return `Ok()` for unaligned pointers!
384 if self.check_defined(ptr
, size
).is_err() {
385 // This inflates undefined bytes to the entire scalar, even if only a few
386 // bytes are undefined.
387 return Ok(ScalarMaybeUndef
::Undef
);
389 // Now we do the actual reading.
390 let bits
= read_target_uint(cx
.data_layout().endian
, bytes
).unwrap();
391 // See if we got a pointer.
392 if size
!= cx
.data_layout().pointer_size
{
393 // *Now*, we better make sure that the inside is free of relocations too.
394 self.check_relocations(cx
, ptr
, size
)?
;
396 match self.relocations
.get(&ptr
.offset
) {
397 Some(&(tag
, alloc_id
)) => {
398 let ptr
= Pointer
::new_with_tag(alloc_id
, Size
::from_bytes(bits
as u64), tag
);
399 return Ok(ScalarMaybeUndef
::Scalar(ptr
.into()));
404 // We don't. Just return the bits.
405 Ok(ScalarMaybeUndef
::Scalar(Scalar
::from_uint(bits
, size
)))
408 /// Reads a pointer-sized scalar.
410 /// It is the caller's responsibility to check bounds and alignment beforehand.
411 /// Most likely, you want to call `InterpCx::read_scalar` instead of this method.
412 pub fn read_ptr_sized(
414 cx
: &impl HasDataLayout
,
416 ) -> InterpResult
<'tcx
, ScalarMaybeUndef
<Tag
>> {
417 self.read_scalar(cx
, ptr
, cx
.data_layout().pointer_size
)
420 /// Writes a *non-ZST* scalar.
422 /// ZSTs can't be read for two reasons:
423 /// * byte-order cannot work with zero-element buffers;
424 /// * in order to obtain a `Pointer`, we need to check for ZSTness anyway due to integer
425 /// pointers being valid for ZSTs.
427 /// It is the caller's responsibility to check bounds and alignment beforehand.
428 /// Most likely, you want to call `InterpCx::write_scalar` instead of this method.
431 cx
: &impl HasDataLayout
,
433 val
: ScalarMaybeUndef
<Tag
>,
435 ) -> InterpResult
<'tcx
> {
436 let val
= match val
{
437 ScalarMaybeUndef
::Scalar(scalar
) => scalar
,
438 ScalarMaybeUndef
::Undef
=> {
439 self.mark_definedness(ptr
, type_size
, false);
444 let bytes
= match val
.to_bits_or_ptr(type_size
, cx
) {
445 Err(val
) => val
.offset
.bytes() as u128
,
449 let endian
= cx
.data_layout().endian
;
450 let dst
= self.get_bytes_mut(cx
, ptr
, type_size
)?
;
451 write_target_uint(endian
, dst
, bytes
).unwrap();
453 // See if we have to also write a relocation.
455 Scalar
::Ptr(val
) => {
456 self.relocations
.insert(ptr
.offset
, (val
.tag
, val
.alloc_id
));
464 /// Writes a pointer-sized scalar.
466 /// It is the caller's responsibility to check bounds and alignment beforehand.
467 /// Most likely, you want to call `InterpCx::write_scalar` instead of this method.
468 pub fn write_ptr_sized(
470 cx
: &impl HasDataLayout
,
472 val
: ScalarMaybeUndef
<Tag
>,
473 ) -> InterpResult
<'tcx
> {
474 let ptr_size
= cx
.data_layout().pointer_size
;
475 self.write_scalar(cx
, ptr
, val
, ptr_size
)
480 impl<'tcx
, Tag
: Copy
, Extra
> Allocation
<Tag
, Extra
> {
481 /// Returns all relocations overlapping with the given pointer-offset pair.
482 pub fn get_relocations(
484 cx
: &impl HasDataLayout
,
487 ) -> &[(Size
, (Tag
, AllocId
))] {
488 // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
489 // the beginning of this range.
490 let start
= ptr
.offset
.bytes().saturating_sub(cx
.data_layout().pointer_size
.bytes() - 1);
491 let end
= ptr
.offset
+ size
; // This does overflow checking.
492 self.relocations
.range(Size
::from_bytes(start
)..end
)
495 /// Checks that there are no relocations overlapping with the given range.
497 fn check_relocations(
499 cx
: &impl HasDataLayout
,
502 ) -> InterpResult
<'tcx
> {
503 if self.get_relocations(cx
, ptr
, size
).is_empty() {
506 throw_unsup
!(ReadPointerAsBytes
)
510 /// Removes all relocations inside the given range.
511 /// If there are relocations overlapping with the edges, they
512 /// are removed as well *and* the bytes they cover are marked as
513 /// uninitialized. This is a somewhat odd "spooky action at a distance",
514 /// but it allows strictly more code to run than if we would just error
515 /// immediately in that case.
516 fn clear_relocations(
518 cx
: &impl HasDataLayout
,
521 ) -> InterpResult
<'tcx
> {
522 // Find the start and end of the given range and its outermost relocations.
523 let (first
, last
) = {
524 // Find all relocations overlapping the given range.
525 let relocations
= self.get_relocations(cx
, ptr
, size
);
526 if relocations
.is_empty() {
531 relocations
.first().unwrap().0,
532 relocations
.last().unwrap().0 + cx
.data_layout().pointer_size
,
535 let start
= ptr
.offset
;
536 let end
= start
+ size
;
538 // Mark parts of the outermost relocations as undefined if they partially fall outside the
541 self.undef_mask
.set_range(first
, start
, false);
544 self.undef_mask
.set_range(end
, last
, false);
547 // Forget all the relocations.
548 self.relocations
.remove_range(first
..last
);
553 /// Errors if there are relocations overlapping with the edges of the
554 /// given memory range.
556 fn check_relocation_edges(
558 cx
: &impl HasDataLayout
,
561 ) -> InterpResult
<'tcx
> {
562 self.check_relocations(cx
, ptr
, Size
::ZERO
)?
;
563 self.check_relocations(cx
, ptr
.offset(size
, cx
)?
, Size
::ZERO
)?
;
569 impl<'tcx
, Tag
, Extra
> Allocation
<Tag
, Extra
> {
570 /// Checks that a range of bytes is defined. If not, returns the `ReadUndefBytes`
571 /// error which will report the first byte which is undefined.
573 fn check_defined(&self, ptr
: Pointer
<Tag
>, size
: Size
) -> InterpResult
<'tcx
> {
575 .is_range_defined(ptr
.offset
, ptr
.offset
+ size
)
576 .or_else(|idx
| throw_unsup
!(ReadUndefBytes(idx
)))
579 pub fn mark_definedness(&mut self, ptr
: Pointer
<Tag
>, size
: Size
, new_state
: bool
) {
580 if size
.bytes() == 0 {
583 self.undef_mask
.set_range(ptr
.offset
, ptr
.offset
+ size
, new_state
);
587 /// Run-length encoding of the undef mask.
588 /// Used to copy parts of a mask multiple times to another allocation.
589 pub struct AllocationDefinedness
{
590 /// The definedness of the first range.
592 /// The lengths of ranges that are run-length encoded.
593 /// The definedness of the ranges alternate starting with `initial`.
594 ranges
: smallvec
::SmallVec
<[u64; 1]>,
597 impl AllocationDefinedness
{
598 pub fn all_bytes_undef(&self) -> bool
{
599 // The `ranges` are run-length encoded and of alternating definedness.
600 // So if `ranges.len() > 1` then the second block is a range of defined.
601 !self.initial
&& self.ranges
.len() == 1
605 /// Transferring the definedness mask to other allocations.
606 impl<Tag
, Extra
> Allocation
<Tag
, Extra
> {
607 /// Creates a run-length encoding of the undef mask.
608 pub fn compress_undef_range(&self, src
: Pointer
<Tag
>, size
: Size
) -> AllocationDefinedness
{
609 // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
610 // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
611 // the source and write it to the destination. Even if we optimized the memory accesses,
612 // we'd be doing all of this `repeat` times.
613 // Therefore we precompute a compressed version of the undef mask of the source value and
614 // then write it back `repeat` times without computing any more information from the source.
616 // A precomputed cache for ranges of defined/undefined bits
617 // 0000010010001110 will become
618 // `[5, 1, 2, 1, 3, 3, 1]`,
619 // where each element toggles the state.
621 let mut ranges
= smallvec
::SmallVec
::<[u64; 1]>::new();
622 let initial
= self.undef_mask
.get(src
.offset
);
624 let mut cur
= initial
;
626 for i
in 1..size
.bytes() {
627 // FIXME: optimize to bitshift the current undef block's bits and read the top bit.
628 if self.undef_mask
.get(src
.offset
+ Size
::from_bytes(i
)) == cur
{
631 ranges
.push(cur_len
);
637 ranges
.push(cur_len
);
639 AllocationDefinedness { ranges, initial }
642 /// Applies multiple instances of the run-length encoding to the undef mask.
643 pub fn mark_compressed_undef_range(
645 defined
: &AllocationDefinedness
,
650 // An optimization where we can just overwrite an entire range of definedness bits if
651 // they are going to be uniformly `1` or `0`.
652 if defined
.ranges
.len() <= 1 {
653 self.undef_mask
.set_range_inbounds(
655 dest
.offset
+ size
* repeat
,
661 for mut j
in 0..repeat
{
663 j
+= dest
.offset
.bytes();
664 let mut cur
= defined
.initial
;
665 for range
in &defined
.ranges
{
668 self.undef_mask
.set_range_inbounds(
669 Size
::from_bytes(old_j
),
680 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
681 pub struct Relocations
<Tag
= (), Id
= AllocId
>(SortedMap
<Size
, (Tag
, Id
)>);
683 impl<Tag
, Id
> Relocations
<Tag
, Id
> {
684 pub fn new() -> Self {
685 Relocations(SortedMap
::new())
688 // The caller must guarantee that the given relocations are already sorted
689 // by address and contain no duplicates.
690 pub fn from_presorted(r
: Vec
<(Size
, (Tag
, Id
))>) -> Self {
691 Relocations(SortedMap
::from_presorted_elements(r
))
695 impl<Tag
> Deref
for Relocations
<Tag
> {
696 type Target
= SortedMap
<Size
, (Tag
, AllocId
)>;
698 fn deref(&self) -> &Self::Target
{
703 impl<Tag
> DerefMut
for Relocations
<Tag
> {
704 fn deref_mut(&mut self) -> &mut Self::Target
{
709 /// A partial, owned list of relocations to transfer into another allocation.
710 pub struct AllocationRelocations
<Tag
> {
711 relative_relocations
: Vec
<(Size
, (Tag
, AllocId
))>,
714 impl<Tag
: Copy
, Extra
> Allocation
<Tag
, Extra
> {
715 pub fn prepare_relocation_copy(
717 cx
: &impl HasDataLayout
,
722 ) -> AllocationRelocations
<Tag
> {
723 let relocations
= self.get_relocations(cx
, src
, size
);
724 if relocations
.is_empty() {
725 return AllocationRelocations { relative_relocations: Vec::new() }
;
728 let mut new_relocations
= Vec
::with_capacity(relocations
.len() * (length
as usize));
731 new_relocations
.extend(relocations
.iter().map(|&(offset
, reloc
)| {
732 // compute offset for current repetition
733 let dest_offset
= dest
.offset
+ (i
* size
);
735 // shift offsets from source allocation to destination allocation
736 offset
+ dest_offset
- src
.offset
,
742 AllocationRelocations { relative_relocations: new_relocations }
745 /// Applies a relocation copy.
746 /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected
747 /// to be clear of relocations.
748 pub fn mark_relocation_range(&mut self, relocations
: AllocationRelocations
<Tag
>) {
749 self.relocations
.insert_presorted(relocations
.relative_relocations
);
753 ////////////////////////////////////////////////////////////////////////////////
754 // Undefined byte tracking
755 ////////////////////////////////////////////////////////////////////////////////
759 /// A bitmask where each bit refers to the byte with the same index. If the bit is `true`, the byte
760 /// is defined. If it is `false` the byte is undefined.
773 pub struct UndefMask
{
779 pub const BLOCK_SIZE
: u64 = 64;
781 pub fn new(size
: Size
, state
: bool
) -> Self {
782 let mut m
= UndefMask { blocks: vec![], len: Size::ZERO }
;
787 /// Checks whether the range `start..end` (end-exclusive) is entirely defined.
789 /// Returns `Ok(())` if it's defined. Otherwise returns the index of the byte
790 /// at which the first undefined access begins.
792 pub fn is_range_defined(&self, start
: Size
, end
: Size
) -> Result
<(), Size
> {
794 return Err(self.len
);
797 // FIXME(oli-obk): optimize this for allocations larger than a block.
798 let idx
= (start
.bytes()..end
.bytes()).map(|i
| Size
::from_bytes(i
)).find(|&i
| !self.get(i
));
801 Some(idx
) => Err(idx
),
806 pub fn set_range(&mut self, start
: Size
, end
: Size
, new_state
: bool
) {
809 self.grow(end
- len
, new_state
);
811 self.set_range_inbounds(start
, end
, new_state
);
814 pub fn set_range_inbounds(&mut self, start
: Size
, end
: Size
, new_state
: bool
) {
815 let (blocka
, bita
) = bit_index(start
);
816 let (blockb
, bitb
) = bit_index(end
);
817 if blocka
== blockb
{
818 // First set all bits except the first `bita`,
819 // then unset the last `64 - bitb` bits.
820 let range
= if bitb
== 0 {
823 (u64::MAX
<< bita
) & (u64::MAX
>> (64 - bitb
))
826 self.blocks
[blocka
] |= range
;
828 self.blocks
[blocka
] &= !range
;
832 // across block boundaries
834 // Set `bita..64` to `1`.
835 self.blocks
[blocka
] |= u64::MAX
<< bita
;
836 // Set `0..bitb` to `1`.
838 self.blocks
[blockb
] |= u64::MAX
>> (64 - bitb
);
840 // Fill in all the other blocks (much faster than one bit at a time).
841 for block
in (blocka
+ 1)..blockb
{
842 self.blocks
[block
] = u64::MAX
;
845 // Set `bita..64` to `0`.
846 self.blocks
[blocka
] &= !(u64::MAX
<< bita
);
847 // Set `0..bitb` to `0`.
849 self.blocks
[blockb
] &= !(u64::MAX
>> (64 - bitb
));
851 // Fill in all the other blocks (much faster than one bit at a time).
852 for block
in (blocka
+ 1)..blockb
{
853 self.blocks
[block
] = 0;
859 pub fn get(&self, i
: Size
) -> bool
{
860 let (block
, bit
) = bit_index(i
);
861 (self.blocks
[block
] & (1 << bit
)) != 0
865 pub fn set(&mut self, i
: Size
, new_state
: bool
) {
866 let (block
, bit
) = bit_index(i
);
867 self.set_bit(block
, bit
, new_state
);
871 fn set_bit(&mut self, block
: usize, bit
: usize, new_state
: bool
) {
873 self.blocks
[block
] |= 1 << bit
;
875 self.blocks
[block
] &= !(1 << bit
);
879 pub fn grow(&mut self, amount
: Size
, new_state
: bool
) {
880 if amount
.bytes() == 0 {
883 let unused_trailing_bits
= self.blocks
.len() as u64 * Self::BLOCK_SIZE
- self.len
.bytes();
884 if amount
.bytes() > unused_trailing_bits
{
885 let additional_blocks
= amount
.bytes() / Self::BLOCK_SIZE
+ 1;
886 assert_eq
!(additional_blocks
as usize as u64, additional_blocks
);
888 // FIXME(oli-obk): optimize this by repeating `new_state as Block`.
889 iter
::repeat(0).take(additional_blocks
as usize),
892 let start
= self.len
;
894 self.set_range_inbounds(start
, start
+ amount
, new_state
);
899 fn bit_index(bits
: Size
) -> (usize, usize) {
900 let bits
= bits
.bytes();
901 let a
= bits
/ UndefMask
::BLOCK_SIZE
;
902 let b
= bits
% UndefMask
::BLOCK_SIZE
;
903 assert_eq
!(a
as usize as u64, a
);
904 assert_eq
!(b
as usize as u64, b
);
905 (a
as usize, b
as usize)