@@ -115,14 +115,14 @@ impl MmapBitVec {
115
115
/// The header_size must be specified (as it isn't stored in the file to
116
116
/// allow the magic bytes to be set) and there is an optional read_only
117
117
/// 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 >
119
119
where
120
120
P : AsRef < Path > ,
121
121
{
122
122
// we have to open with write=true to satisfy MmapMut (which we're
123
123
// using because there's no generic over both MmapMut and Mmap so
124
124
// 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) ?;
126
126
127
127
// read the magic bytes and (optionally) check if it matches
128
128
let mut file_magic = [ 0 ; 2 ] ;
@@ -166,11 +166,17 @@ impl MmapBitVec {
166
166
) ) ;
167
167
}
168
168
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
+ } ;
171
177
172
178
Ok ( MmapBitVec {
173
- mmap : CommonMmap :: Mmap ( mmap ) ,
179
+ mmap,
174
180
size : size as usize ,
175
181
header : header. into_boxed_slice ( ) ,
176
182
} )
@@ -648,7 +654,7 @@ mod test {
648
654
drop ( b) ;
649
655
assert ! ( Path :: new( "./test" ) . exists( ) ) ;
650
656
651
- let b = MmapBitVec :: open ( "./test" , Some ( b"!!" ) ) . unwrap ( ) ;
657
+ let b = MmapBitVec :: open ( "./test" , Some ( b"!!" ) , true ) . unwrap ( ) ;
652
658
assert ! ( !b. get( 1 ) ) ;
653
659
assert ! ( b. get( 2 ) ) ;
654
660
assert ! ( !b. get( 100 ) ) ;
0 commit comments