Skip to content

Commit 7588157

Browse files
Roderick Boveeboydgreenfield
authored andcommitted
Add support for opening MmapBitvec in write mode
1 parent 690d3e7 commit 7588157

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/bloom.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ impl BloomFilter {
5353
let bitvec = match filename {
5454
Some(filename) => {
5555
if Path::exists(filename.as_ref()) {
56-
MmapBitVec::open(&filename, Some(b"!!"))?
56+
MmapBitVec::open(&filename, Some(b"!!"), false)?
5757
} else {
5858
MmapBitVec::create(&filename, bits, *b"!!", &header)?
5959
}

src/mmap_bitvec.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -115,14 +115,14 @@ impl MmapBitVec {
115115
/// The header_size must be specified (as it isn't stored in the file to
116116
/// allow the magic bytes to be set) and there is an optional read_only
117117
/// property that will lock the underlying mmap from writing.
118-
pub fn open<P>(filename: P, magic: Option<&[u8; 2]>) -> Result<Self, io::Error>
118+
pub fn open<P>(filename: P, magic: Option<&[u8; 2]>, read_only: bool) -> Result<Self, io::Error>
119119
where
120120
P: AsRef<Path>,
121121
{
122122
// we have to open with write=true to satisfy MmapMut (which we're
123123
// using because there's no generic over both MmapMut and Mmap so
124124
// picking one simplifies the types)
125-
let mut file = OpenOptions::new().read(true).write(false).open(filename)?;
125+
let mut file = OpenOptions::new().read(true).write(!read_only).open(filename)?;
126126

127127
// read the magic bytes and (optionally) check if it matches
128128
let mut file_magic = [0; 2];
@@ -166,11 +166,17 @@ impl MmapBitVec {
166166
));
167167
}
168168

169-
// load the mmap itself and return the whole shebang
170-
let mmap = unsafe { MmapOptions::new().offset(total_header_size).map(&file) }?;
169+
let mmap = if read_only {
170+
// load the mmap itself and return the whole shebang
171+
let mmap = unsafe { MmapOptions::new().offset(total_header_size).map(&file) }?;
172+
CommonMmap::Mmap(mmap)
173+
} else {
174+
let mmap = unsafe { MmapOptions::new().offset(total_header_size).map_mut(&file) }?;
175+
CommonMmap::MmapMut(mmap)
176+
};
171177

172178
Ok(MmapBitVec {
173-
mmap: CommonMmap::Mmap(mmap),
179+
mmap,
174180
size: size as usize,
175181
header: header.into_boxed_slice(),
176182
})
@@ -648,7 +654,7 @@ mod test {
648654
drop(b);
649655
assert!(Path::new("./test").exists());
650656

651-
let b = MmapBitVec::open("./test", Some(b"!!")).unwrap();
657+
let b = MmapBitVec::open("./test", Some(b"!!"), true).unwrap();
652658
assert!(!b.get(1));
653659
assert!(b.get(2));
654660
assert!(!b.get(100));

0 commit comments

Comments
 (0)