]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/interpret/allocation.rs
Rollup merge of #58273 - taiki-e:rename-dependency, r=matthewjasper
[rust.git] / src / librustc / mir / interpret / allocation.rs
1 //! The virtual memory representation of the MIR interpreter.
2
3 use super::{
4     Pointer, EvalResult, AllocId, ScalarMaybeUndef, write_target_uint, read_target_uint, Scalar,
5     truncate,
6 };
7
8 use crate::ty::layout::{Size, Align};
9 use syntax::ast::Mutability;
10 use std::iter;
11 use crate::mir;
12 use std::ops::{Deref, DerefMut};
13 use rustc_data_structures::sorted_map::SortedMap;
14 use rustc_target::abi::HasDataLayout;
15
16 /// Used by `check_bounds` to indicate whether the pointer needs to be just inbounds
17 /// or also inbounds of a *live* allocation.
18 #[derive(Debug, Copy, Clone, RustcEncodable, RustcDecodable)]
19 pub enum InboundsCheck {
20     Live,
21     MaybeDead,
22 }
23
24 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
25 pub struct Allocation<Tag=(),Extra=()> {
26     /// The actual bytes of the allocation.
27     /// Note that the bytes of a pointer represent the offset of the pointer
28     pub bytes: Vec<u8>,
29     /// Maps from byte addresses to extra data for each pointer.
30     /// Only the first byte of a pointer is inserted into the map; i.e.,
31     /// every entry in this map applies to `pointer_size` consecutive bytes starting
32     /// at the given offset.
33     pub relocations: Relocations<Tag>,
34     /// Denotes undefined memory. Reading from undefined memory is forbidden in miri
35     pub undef_mask: UndefMask,
36     /// The alignment of the allocation to detect unaligned reads.
37     pub align: Align,
38     /// Whether the allocation is mutable.
39     /// Also used by codegen to determine if a static should be put into mutable memory,
40     /// which happens for `static mut` and `static` with interior mutability.
41     pub mutability: Mutability,
42     /// Extra state for the machine.
43     pub extra: Extra,
44 }
45
46
47 pub trait AllocationExtra<Tag, MemoryExtra>: ::std::fmt::Debug + Clone {
48     /// Hook to initialize the extra data when an allocation gets created.
49     fn memory_allocated(
50         _size: Size,
51         _memory_extra: &MemoryExtra
52     ) -> Self;
53
54     /// Hook for performing extra checks on a memory read access.
55     ///
56     /// Takes read-only access to the allocation so we can keep all the memory read
57     /// operations take `&self`. Use a `RefCell` in `AllocExtra` if you
58     /// need to mutate.
59     #[inline(always)]
60     fn memory_read(
61         _alloc: &Allocation<Tag, Self>,
62         _ptr: Pointer<Tag>,
63         _size: Size,
64     ) -> EvalResult<'tcx> {
65         Ok(())
66     }
67
68     /// Hook for performing extra checks on a memory write access.
69     #[inline(always)]
70     fn memory_written(
71         _alloc: &mut Allocation<Tag, Self>,
72         _ptr: Pointer<Tag>,
73         _size: Size,
74     ) -> EvalResult<'tcx> {
75         Ok(())
76     }
77
78     /// Hook for performing extra checks on a memory deallocation.
79     /// `size` will be the size of the allocation.
80     #[inline(always)]
81     fn memory_deallocated(
82         _alloc: &mut Allocation<Tag, Self>,
83         _ptr: Pointer<Tag>,
84         _size: Size,
85     ) -> EvalResult<'tcx> {
86         Ok(())
87     }
88 }
89
90 impl AllocationExtra<(), ()> for () {
91     #[inline(always)]
92     fn memory_allocated(
93         _size: Size,
94         _memory_extra: &()
95     ) -> Self {
96         ()
97     }
98 }
99
100 impl<Tag, Extra> Allocation<Tag, Extra> {
101     /// Creates a read-only allocation initialized by the given bytes
102     pub fn from_bytes(slice: &[u8], align: Align, extra: Extra) -> Self {
103         let mut undef_mask = UndefMask::new(Size::ZERO);
104         undef_mask.grow(Size::from_bytes(slice.len() as u64), true);
105         Self {
106             bytes: slice.to_owned(),
107             relocations: Relocations::new(),
108             undef_mask,
109             align,
110             mutability: Mutability::Immutable,
111             extra,
112         }
113     }
114
115     pub fn from_byte_aligned_bytes(slice: &[u8], extra: Extra) -> Self {
116         Allocation::from_bytes(slice, Align::from_bytes(1).unwrap(), extra)
117     }
118
119     pub fn undef(size: Size, align: Align, extra: Extra) -> Self {
120         assert_eq!(size.bytes() as usize as u64, size.bytes());
121         Allocation {
122             bytes: vec![0; size.bytes() as usize],
123             relocations: Relocations::new(),
124             undef_mask: UndefMask::new(size),
125             align,
126             mutability: Mutability::Mutable,
127             extra,
128         }
129     }
130 }
131
132 impl<'tcx> ::serialize::UseSpecializedDecodable for &'tcx Allocation {}
133
134 /// Alignment and bounds checks
135 impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
136     /// Checks if the pointer is "in-bounds". Notice that a pointer pointing at the end
137     /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
138     /// in-bounds!  This follows C's/LLVM's rules.
139     /// If you want to check bounds before doing a memory access, better use `check_bounds`.
140     fn check_bounds_ptr(
141         &self,
142         ptr: Pointer<Tag>,
143     ) -> EvalResult<'tcx> {
144         let allocation_size = self.bytes.len() as u64;
145         ptr.check_in_alloc(Size::from_bytes(allocation_size), InboundsCheck::Live)
146     }
147
148     /// Checks if the memory range beginning at `ptr` and of size `Size` is "in-bounds".
149     #[inline(always)]
150     pub fn check_bounds(
151         &self,
152         cx: &impl HasDataLayout,
153         ptr: Pointer<Tag>,
154         size: Size,
155     ) -> EvalResult<'tcx> {
156         // if ptr.offset is in bounds, then so is ptr (because offset checks for overflow)
157         self.check_bounds_ptr(ptr.offset(size, cx)?)
158     }
159 }
160
161 /// Byte accessors
162 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
163     /// The last argument controls whether we error out when there are undefined
164     /// or pointer bytes. You should never call this, call `get_bytes` or
165     /// `get_bytes_with_undef_and_ptr` instead,
166     ///
167     /// This function also guarantees that the resulting pointer will remain stable
168     /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies
169     /// on that.
170     fn get_bytes_internal<MemoryExtra>(
171         &self,
172         cx: &impl HasDataLayout,
173         ptr: Pointer<Tag>,
174         size: Size,
175         check_defined_and_ptr: bool,
176     ) -> EvalResult<'tcx, &[u8]>
177         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
178         where Extra: AllocationExtra<Tag, MemoryExtra>
179     {
180         self.check_bounds(cx, ptr, size)?;
181
182         if check_defined_and_ptr {
183             self.check_defined(ptr, size)?;
184             self.check_relocations(cx, ptr, size)?;
185         } else {
186             // We still don't want relocations on the *edges*
187             self.check_relocation_edges(cx, ptr, size)?;
188         }
189
190         AllocationExtra::memory_read(self, ptr, size)?;
191
192         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
193         assert_eq!(size.bytes() as usize as u64, size.bytes());
194         let offset = ptr.offset.bytes() as usize;
195         Ok(&self.bytes[offset..offset + size.bytes() as usize])
196     }
197
198     #[inline]
199     pub fn get_bytes<MemoryExtra>(
200         &self,
201         cx: &impl HasDataLayout,
202         ptr: Pointer<Tag>,
203         size: Size,
204     ) -> EvalResult<'tcx, &[u8]>
205         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
206         where Extra: AllocationExtra<Tag, MemoryExtra>
207     {
208         self.get_bytes_internal(cx, ptr, size, true)
209     }
210
211     /// It is the caller's responsibility to handle undefined and pointer bytes.
212     /// However, this still checks that there are no relocations on the *edges*.
213     #[inline]
214     pub fn get_bytes_with_undef_and_ptr<MemoryExtra>(
215         &self,
216         cx: &impl HasDataLayout,
217         ptr: Pointer<Tag>,
218         size: Size,
219     ) -> EvalResult<'tcx, &[u8]>
220         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
221         where Extra: AllocationExtra<Tag, MemoryExtra>
222     {
223         self.get_bytes_internal(cx, ptr, size, false)
224     }
225
226     /// Just calling this already marks everything as defined and removes relocations,
227     /// so be sure to actually put data there!
228     pub fn get_bytes_mut<MemoryExtra>(
229         &mut self,
230         cx: &impl HasDataLayout,
231         ptr: Pointer<Tag>,
232         size: Size,
233     ) -> EvalResult<'tcx, &mut [u8]>
234         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
235         where Extra: AllocationExtra<Tag, MemoryExtra>
236     {
237         assert_ne!(size.bytes(), 0, "0-sized accesses should never even get a `Pointer`");
238         self.check_bounds(cx, ptr, size)?;
239
240         self.mark_definedness(ptr, size, true)?;
241         self.clear_relocations(cx, ptr, size)?;
242
243         AllocationExtra::memory_written(self, ptr, size)?;
244
245         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
246         assert_eq!(size.bytes() as usize as u64, size.bytes());
247         let offset = ptr.offset.bytes() as usize;
248         Ok(&mut self.bytes[offset..offset + size.bytes() as usize])
249     }
250 }
251
252 /// Reading and writing
253 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
254     /// Reads bytes until a `0` is encountered. Will error if the end of the allocation is reached
255     /// before a `0` is found.
256     pub fn read_c_str<MemoryExtra>(
257         &self,
258         cx: &impl HasDataLayout,
259         ptr: Pointer<Tag>,
260     ) -> EvalResult<'tcx, &[u8]>
261         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
262         where Extra: AllocationExtra<Tag, MemoryExtra>
263     {
264         assert_eq!(ptr.offset.bytes() as usize as u64, ptr.offset.bytes());
265         let offset = ptr.offset.bytes() as usize;
266         match self.bytes[offset..].iter().position(|&c| c == 0) {
267             Some(size) => {
268                 let size_with_null = Size::from_bytes((size + 1) as u64);
269                 // Go through `get_bytes` for checks and AllocationExtra hooks.
270                 // We read the null, so we include it in the request, but we want it removed
271                 // from the result!
272                 Ok(&self.get_bytes(cx, ptr, size_with_null)?[..size])
273             }
274             None => err!(UnterminatedCString(ptr.erase_tag())),
275         }
276     }
277
278     /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a
279     /// relocation. If `allow_ptr_and_undef` is `false`, also enforces that the memory in the
280     /// given range contains neither relocations nor undef bytes.
281     pub fn check_bytes<MemoryExtra>(
282         &self,
283         cx: &impl HasDataLayout,
284         ptr: Pointer<Tag>,
285         size: Size,
286         allow_ptr_and_undef: bool,
287     ) -> EvalResult<'tcx>
288         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
289         where Extra: AllocationExtra<Tag, MemoryExtra>
290     {
291         // Check bounds and relocations on the edges
292         self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
293         // Check undef and ptr
294         if !allow_ptr_and_undef {
295             self.check_defined(ptr, size)?;
296             self.check_relocations(cx, ptr, size)?;
297         }
298         Ok(())
299     }
300
301     /// Writes `src` to the memory starting at `ptr.offset`.
302     ///
303     /// Will do bounds checks on the allocation.
304     pub fn write_bytes<MemoryExtra>(
305         &mut self,
306         cx: &impl HasDataLayout,
307         ptr: Pointer<Tag>,
308         src: &[u8],
309     ) -> EvalResult<'tcx>
310         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
311         where Extra: AllocationExtra<Tag, MemoryExtra>
312     {
313         let bytes = self.get_bytes_mut(cx, ptr, Size::from_bytes(src.len() as u64))?;
314         bytes.clone_from_slice(src);
315         Ok(())
316     }
317
318     /// Sets `count` bytes starting at `ptr.offset` with `val`. Basically `memset`.
319     pub fn write_repeat<MemoryExtra>(
320         &mut self,
321         cx: &impl HasDataLayout,
322         ptr: Pointer<Tag>,
323         val: u8,
324         count: Size
325     ) -> EvalResult<'tcx>
326         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
327         where Extra: AllocationExtra<Tag, MemoryExtra>
328     {
329         let bytes = self.get_bytes_mut(cx, ptr, count)?;
330         for b in bytes {
331             *b = val;
332         }
333         Ok(())
334     }
335
336     /// Read a *non-ZST* scalar
337     ///
338     /// zsts can't be read out of two reasons:
339     /// * byteorder cannot work with zero element buffers
340     /// * in oder to obtain a `Pointer` we need to check for ZSTness anyway due to integer pointers
341     ///   being valid for ZSTs
342     ///
343     /// Note: This function does not do *any* alignment checks, you need to do these before calling
344     pub fn read_scalar<MemoryExtra>(
345         &self,
346         cx: &impl HasDataLayout,
347         ptr: Pointer<Tag>,
348         size: Size
349     ) -> EvalResult<'tcx, ScalarMaybeUndef<Tag>>
350         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
351         where Extra: AllocationExtra<Tag, MemoryExtra>
352     {
353         // get_bytes_unchecked tests relocation edges
354         let bytes = self.get_bytes_with_undef_and_ptr(cx, ptr, size)?;
355         // Undef check happens *after* we established that the alignment is correct.
356         // We must not return Ok() for unaligned pointers!
357         if self.check_defined(ptr, size).is_err() {
358             // this inflates undefined bytes to the entire scalar, even if only a few
359             // bytes are undefined
360             return Ok(ScalarMaybeUndef::Undef);
361         }
362         // Now we do the actual reading
363         let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap();
364         // See if we got a pointer
365         if size != cx.data_layout().pointer_size {
366             // *Now* better make sure that the inside also is free of relocations.
367             self.check_relocations(cx, ptr, size)?;
368         } else {
369             match self.relocations.get(&ptr.offset) {
370                 Some(&(tag, alloc_id)) => {
371                     let ptr = Pointer::new_with_tag(alloc_id, Size::from_bytes(bits as u64), tag);
372                     return Ok(ScalarMaybeUndef::Scalar(ptr.into()))
373                 }
374                 None => {},
375             }
376         }
377         // We don't. Just return the bits.
378         Ok(ScalarMaybeUndef::Scalar(Scalar::from_uint(bits, size)))
379     }
380
381     /// Note: This function does not do *any* alignment checks, you need to do these before calling
382     pub fn read_ptr_sized<MemoryExtra>(
383         &self,
384         cx: &impl HasDataLayout,
385         ptr: Pointer<Tag>,
386     ) -> EvalResult<'tcx, ScalarMaybeUndef<Tag>>
387         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
388         where Extra: AllocationExtra<Tag, MemoryExtra>
389     {
390         self.read_scalar(cx, ptr, cx.data_layout().pointer_size)
391     }
392
393     /// Write a *non-ZST* scalar
394     ///
395     /// zsts can't be read out of two reasons:
396     /// * byteorder cannot work with zero element buffers
397     /// * in oder to obtain a `Pointer` we need to check for ZSTness anyway due to integer pointers
398     ///   being valid for ZSTs
399     ///
400     /// Note: This function does not do *any* alignment checks, you need to do these before calling
401     pub fn write_scalar<MemoryExtra>(
402         &mut self,
403         cx: &impl HasDataLayout,
404         ptr: Pointer<Tag>,
405         val: ScalarMaybeUndef<Tag>,
406         type_size: Size,
407     ) -> EvalResult<'tcx>
408         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
409         where Extra: AllocationExtra<Tag, MemoryExtra>
410     {
411         let val = match val {
412             ScalarMaybeUndef::Scalar(scalar) => scalar,
413             ScalarMaybeUndef::Undef => return self.mark_definedness(ptr, type_size, false),
414         };
415
416         let bytes = match val {
417             Scalar::Ptr(val) => {
418                 assert_eq!(type_size, cx.data_layout().pointer_size);
419                 val.offset.bytes() as u128
420             }
421
422             Scalar::Bits { bits, size } => {
423                 assert_eq!(size as u64, type_size.bytes());
424                 debug_assert_eq!(truncate(bits, Size::from_bytes(size.into())), bits,
425                     "Unexpected value of size {} when writing to memory", size);
426                 bits
427             },
428         };
429
430         let endian = cx.data_layout().endian;
431         let dst = self.get_bytes_mut(cx, ptr, type_size)?;
432         write_target_uint(endian, dst, bytes).unwrap();
433
434         // See if we have to also write a relocation
435         match val {
436             Scalar::Ptr(val) => {
437                 self.relocations.insert(
438                     ptr.offset,
439                     (val.tag, val.alloc_id),
440                 );
441             }
442             _ => {}
443         }
444
445         Ok(())
446     }
447
448     /// Note: This function does not do *any* alignment checks, you need to do these before calling
449     pub fn write_ptr_sized<MemoryExtra>(
450         &mut self,
451         cx: &impl HasDataLayout,
452         ptr: Pointer<Tag>,
453         val: ScalarMaybeUndef<Tag>
454     ) -> EvalResult<'tcx>
455         // FIXME: Working around https://github.com/rust-lang/rust/issues/56209
456         where Extra: AllocationExtra<Tag, MemoryExtra>
457     {
458         let ptr_size = cx.data_layout().pointer_size;
459         self.write_scalar(cx, ptr.into(), val, ptr_size)
460     }
461 }
462
463 /// Relocations
464 impl<'tcx, Tag: Copy, Extra> Allocation<Tag, Extra> {
465     /// Returns all relocations overlapping with the given ptr-offset pair.
466     pub fn relocations(
467         &self,
468         cx: &impl HasDataLayout,
469         ptr: Pointer<Tag>,
470         size: Size,
471     ) -> &[(Size, (Tag, AllocId))] {
472         // We have to go back `pointer_size - 1` bytes, as that one would still overlap with
473         // the beginning of this range.
474         let start = ptr.offset.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1);
475         let end = ptr.offset + size; // this does overflow checking
476         self.relocations.range(Size::from_bytes(start)..end)
477     }
478
479     /// Checks that there are no relocations overlapping with the given range.
480     #[inline(always)]
481     fn check_relocations(
482         &self,
483         cx: &impl HasDataLayout,
484         ptr: Pointer<Tag>,
485         size: Size,
486     ) -> EvalResult<'tcx> {
487         if self.relocations(cx, ptr, size).is_empty() {
488             Ok(())
489         } else {
490             err!(ReadPointerAsBytes)
491         }
492     }
493
494     /// Removes all relocations inside the given range.
495     /// If there are relocations overlapping with the edges, they
496     /// are removed as well *and* the bytes they cover are marked as
497     /// uninitialized. This is a somewhat odd "spooky action at a distance",
498     /// but it allows strictly more code to run than if we would just error
499     /// immediately in that case.
500     fn clear_relocations(
501         &mut self,
502         cx: &impl HasDataLayout,
503         ptr: Pointer<Tag>,
504         size: Size,
505     ) -> EvalResult<'tcx> {
506         // Find the start and end of the given range and its outermost relocations.
507         let (first, last) = {
508             // Find all relocations overlapping the given range.
509             let relocations = self.relocations(cx, ptr, size);
510             if relocations.is_empty() {
511                 return Ok(());
512             }
513
514             (relocations.first().unwrap().0,
515              relocations.last().unwrap().0 + cx.data_layout().pointer_size)
516         };
517         let start = ptr.offset;
518         let end = start + size;
519
520         // Mark parts of the outermost relocations as undefined if they partially fall outside the
521         // given range.
522         if first < start {
523             self.undef_mask.set_range(first, start, false);
524         }
525         if last > end {
526             self.undef_mask.set_range(end, last, false);
527         }
528
529         // Forget all the relocations.
530         self.relocations.remove_range(first..last);
531
532         Ok(())
533     }
534
535     /// Error if there are relocations overlapping with the edges of the
536     /// given memory range.
537     #[inline]
538     fn check_relocation_edges(
539         &self,
540         cx: &impl HasDataLayout,
541         ptr: Pointer<Tag>,
542         size: Size,
543     ) -> EvalResult<'tcx> {
544         self.check_relocations(cx, ptr, Size::ZERO)?;
545         self.check_relocations(cx, ptr.offset(size, cx)?, Size::ZERO)?;
546         Ok(())
547     }
548 }
549
550
551 /// Undefined bytes
552 impl<'tcx, Tag, Extra> Allocation<Tag, Extra> {
553     /// Checks that a range of bytes is defined. If not, returns the `ReadUndefBytes`
554     /// error which will report the first byte which is undefined.
555     #[inline]
556     fn check_defined(&self, ptr: Pointer<Tag>, size: Size) -> EvalResult<'tcx> {
557         self.undef_mask.is_range_defined(
558             ptr.offset,
559             ptr.offset + size,
560         ).or_else(|idx| err!(ReadUndefBytes(idx)))
561     }
562
563     pub fn mark_definedness(
564         &mut self,
565         ptr: Pointer<Tag>,
566         size: Size,
567         new_state: bool,
568     ) -> EvalResult<'tcx> {
569         if size.bytes() == 0 {
570             return Ok(());
571         }
572         self.undef_mask.set_range(
573             ptr.offset,
574             ptr.offset + size,
575             new_state,
576         );
577         Ok(())
578     }
579 }
580
581 /// Relocations
582 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
583 pub struct Relocations<Tag=(), Id=AllocId>(SortedMap<Size, (Tag, Id)>);
584
585 impl<Tag, Id> Relocations<Tag, Id> {
586     pub fn new() -> Self {
587         Relocations(SortedMap::new())
588     }
589
590     // The caller must guarantee that the given relocations are already sorted
591     // by address and contain no duplicates.
592     pub fn from_presorted(r: Vec<(Size, (Tag, Id))>) -> Self {
593         Relocations(SortedMap::from_presorted_elements(r))
594     }
595 }
596
597 impl<Tag> Deref for Relocations<Tag> {
598     type Target = SortedMap<Size, (Tag, AllocId)>;
599
600     fn deref(&self) -> &Self::Target {
601         &self.0
602     }
603 }
604
605 impl<Tag> DerefMut for Relocations<Tag> {
606     fn deref_mut(&mut self) -> &mut Self::Target {
607         &mut self.0
608     }
609 }
610
611 ////////////////////////////////////////////////////////////////////////////////
612 // Undefined byte tracking
613 ////////////////////////////////////////////////////////////////////////////////
614
615 type Block = u64;
616 const BLOCK_SIZE: u64 = 64;
617
618 #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
619 pub struct UndefMask {
620     blocks: Vec<Block>,
621     len: Size,
622 }
623
624 impl_stable_hash_for!(struct mir::interpret::UndefMask{blocks, len});
625
626 impl UndefMask {
627     pub fn new(size: Size) -> Self {
628         let mut m = UndefMask {
629             blocks: vec![],
630             len: Size::ZERO,
631         };
632         m.grow(size, false);
633         m
634     }
635
636     /// Checks whether the range `start..end` (end-exclusive) is entirely defined.
637     ///
638     /// Returns `Ok(())` if it's defined. Otherwise returns the index of the byte
639     /// at which the first undefined access begins.
640     #[inline]
641     pub fn is_range_defined(&self, start: Size, end: Size) -> Result<(), Size> {
642         if end > self.len {
643             return Err(self.len);
644         }
645
646         let idx = (start.bytes()..end.bytes())
647             .map(|i| Size::from_bytes(i))
648             .find(|&i| !self.get(i));
649
650         match idx {
651             Some(idx) => Err(idx),
652             None => Ok(())
653         }
654     }
655
656     pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) {
657         let len = self.len;
658         if end > len {
659             self.grow(end - len, new_state);
660         }
661         self.set_range_inbounds(start, end, new_state);
662     }
663
664     pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) {
665         for i in start.bytes()..end.bytes() {
666             self.set(Size::from_bytes(i), new_state);
667         }
668     }
669
670     #[inline]
671     pub fn get(&self, i: Size) -> bool {
672         let (block, bit) = bit_index(i);
673         (self.blocks[block] & 1 << bit) != 0
674     }
675
676     #[inline]
677     pub fn set(&mut self, i: Size, new_state: bool) {
678         let (block, bit) = bit_index(i);
679         if new_state {
680             self.blocks[block] |= 1 << bit;
681         } else {
682             self.blocks[block] &= !(1 << bit);
683         }
684     }
685
686     pub fn grow(&mut self, amount: Size, new_state: bool) {
687         let unused_trailing_bits = self.blocks.len() as u64 * BLOCK_SIZE - self.len.bytes();
688         if amount.bytes() > unused_trailing_bits {
689             let additional_blocks = amount.bytes() / BLOCK_SIZE + 1;
690             assert_eq!(additional_blocks as usize as u64, additional_blocks);
691             self.blocks.extend(
692                 iter::repeat(0).take(additional_blocks as usize),
693             );
694         }
695         let start = self.len;
696         self.len += amount;
697         self.set_range_inbounds(start, start + amount, new_state);
698     }
699 }
700
701 #[inline]
702 fn bit_index(bits: Size) -> (usize, usize) {
703     let bits = bits.bytes();
704     let a = bits / BLOCK_SIZE;
705     let b = bits % BLOCK_SIZE;
706     assert_eq!(a as usize as u64, a);
707     assert_eq!(b as usize as u64, b);
708     (a as usize, b as usize)
709 }