1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 /// `BitSlice` provides helper methods for treating a `[usize]`
16 fn clear_bit(&mut self, idx
: usize) -> bool
;
17 fn set_bit(&mut self, idx
: usize) -> bool
;
18 fn get_bit(&self, idx
: usize) -> bool
;
21 impl BitSlice
for [usize] {
22 /// Clears bit at `idx` to 0; returns true iff this changed `self.`
23 fn clear_bit(&mut self, idx
: usize) -> bool
{
25 debug
!("clear_bit: words={} idx={}",
26 bits_to_string(words
, words
.len() * mem
::size_of
::<usize>()), bit_str(idx
));
27 let BitLookup { word, bit_in_word, bit_mask }
= bit_lookup(idx
);
28 debug
!("word={} bit_in_word={} bit_mask={}", word
, bit_in_word
, bit_mask
);
29 let oldv
= words
[word
];
30 let newv
= oldv
& !bit_mask
;
35 /// Sets bit at `idx` to 1; returns true iff this changed `self.`
36 fn set_bit(&mut self, idx
: usize) -> bool
{
38 debug
!("set_bit: words={} idx={}",
39 bits_to_string(words
, words
.len() * mem
::size_of
::<usize>()), bit_str(idx
));
40 let BitLookup { word, bit_in_word, bit_mask }
= bit_lookup(idx
);
41 debug
!("word={} bit_in_word={} bit_mask={}", word
, bit_in_word
, bit_mask
);
42 let oldv
= words
[word
];
43 let newv
= oldv
| bit_mask
;
48 /// Extracts value of bit at `idx` in `self`.
49 fn get_bit(&self, idx
: usize) -> bool
{
51 let BitLookup { word, bit_mask, .. }
= bit_lookup(idx
);
52 (words
[word
] & bit_mask
) != 0
57 /// An index of the word holding the bit in original `[usize]` of query.
59 /// Index of the particular bit within the word holding the bit.
61 /// Word with single 1-bit set corresponding to where the bit is located.
66 fn bit_lookup(bit
: usize) -> BitLookup
{
67 let usize_bits
= mem
::size_of
::<usize>() * 8;
68 let word
= bit
/ usize_bits
;
69 let bit_in_word
= bit
% usize_bits
;
70 let bit_mask
= 1 << bit_in_word
;
71 BitLookup { word: word, bit_in_word: bit_in_word, bit_mask: bit_mask }
75 fn bit_str(bit
: usize) -> String
{
77 let lobits
= 1 << (bit
& 0xFF);
78 format
!("[{}:{}-{:02x}]", bit
, byte
, lobits
)
81 pub fn bits_to_string(words
: &[usize], bytes
: usize) -> String
{
82 let mut result
= String
::new();
85 // Note: this is a little endian printout of bytes.
88 for &word
in words
.iter() {
90 for _
in 0..mem
::size_of
::<usize>() {
96 result
.push_str(&format
!("{:02x}", byte
));