simple_sds_sbwt/raw_vector.rs
1//! The basic vector implementing the low-level functionality used by other vectors in the crate.
2
3use crate::serialize::Serialize;
4#[cfg(not(target_family = "wasm"))]
5use crate::serialize::{MappedSlice, MemoryMap, MemoryMapped};
6use crate::bits;
7
8use std::fs::{File, OpenOptions};
9use std::io::{Error, ErrorKind, Seek, SeekFrom};
10use std::path::{Path, PathBuf};
11use std::{cmp, io};
12
13#[cfg(test)]
14mod tests;
15
16//-----------------------------------------------------------------------------
17
18/// Random access to bits and variable-width integers in a bit array.
19///
20/// # Examples
21///
22/// ```
23/// use simple_sds_sbwt::raw_vector::AccessRaw;
24/// use simple_sds_sbwt::bits;
25///
26/// struct Example(Vec<u64>);
27///
28/// impl AccessRaw for Example {
29/// fn bit(&self, bit_offset: usize) -> bool {
30/// let (index, offset) = bits::split_offset(bit_offset);
31/// (self.0[index] & (1u64 << offset)) != 0
32/// }
33///
34/// unsafe fn int(&self, bit_offset: usize, width: usize) -> u64 {
35/// bits::read_int(&self.0, bit_offset, width)
36/// }
37///
38/// fn word(&self, index: usize) -> u64 {
39/// self.0[index]
40/// }
41///
42/// unsafe fn word_unchecked(&self, index: usize) -> u64 {
43/// *self.0.get_unchecked(index)
44/// }
45///
46/// fn is_mutable(&self) -> bool {
47/// true
48/// }
49///
50/// fn set_bit(&mut self, bit_offset: usize, value: bool) {
51/// let (index, offset) = bits::split_offset(bit_offset);
52/// self.0[index] &= !(1u64 << offset);
53/// self.0[index] |= (value as u64) << offset;
54/// }
55///
56/// unsafe fn set_int(&mut self, bit_offset: usize, value: u64, width: usize) {
57/// bits::write_int(&mut self.0, bit_offset, value, width);
58/// }
59/// }
60///
61/// let mut example = Example(vec![0u64; 2]);
62/// assert!(example.is_mutable());
63///
64/// unsafe {
65/// example.set_int(4, 0x33, 8);
66/// example.set_int(63, 2, 2);
67/// }
68/// example.set_bit(72, true);
69/// assert_eq!(example.0[0], 0x330);
70/// assert_eq!(example.0[1], 0x101);
71///
72/// assert!(example.bit(72));
73/// assert!(!example.bit(68));
74/// unsafe {
75/// assert_eq!(example.int(4, 8), 0x33);
76/// assert_eq!(example.int(63, 2), 2);
77/// }
78/// assert_eq!(example.word(1), 0x101);
79/// ```
80pub trait AccessRaw {
81 /// Reads a bit from the array.
82 ///
83 /// # Panics
84 ///
85 /// May panic if `bit_offset` is not a valid offset in the bit array.
86 /// May panic from I/O errors.
87 fn bit(&self, bit_offset: usize) -> bool;
88
89 /// Reads an integer from the container.
90 ///
91 /// # Arguments
92 ///
93 /// * `bit_offset`: Starting offset in the bit array.
94 /// * `width`: The width of the integer in bits.
95 ///
96 /// # Safety
97 ///
98 /// Behavior is undefined if `width > 64`.
99 ///
100 /// # Panics
101 ///
102 /// May panic if `bit_offset + width - 1` is not a valid offset in the bit array.
103 /// May panic from I/O errors.
104 unsafe fn int(&self, bit_offset: usize, width: usize) -> u64;
105
106 /// Reads a 64-bit word from the container.
107 ///
108 /// This may be faster than calling `self.int(index * 64, 64)`.
109 ///
110 /// # Panics
111 ///
112 /// May panic if `index * 64` is not a valid offset in the bit array.
113 /// May panic from I/O errors.
114 fn word(&self, index: usize) -> u64;
115
116 /// Unsafe version of [`AccessRaw::word`] without bounds checks.
117 ///
118 /// # Safety
119 ///
120 /// Behavior is undefined in situations where the safe versions may panic.
121 unsafe fn word_unchecked(&self, index: usize) -> u64;
122
123 /// Returns `true` if the underlying data is mutable.
124 ///
125 /// This is relevant, for example, with memory-mapped vectors, where the underlying file may be opened as read-only.
126 fn is_mutable(&self) -> bool;
127
128 /// Writes a bit to the container.
129 ///
130 /// # Arguments
131 ///
132 /// * `bit_offset`: Offset in the bit array.
133 /// * `value`: The value of the bit.
134 ///
135 /// # Panics
136 ///
137 /// May panic if `bit_offset` is not a valid offset in the bit array.
138 /// May panic if the underlying data is not mutable.
139 /// May panic from I/O errors.
140 fn set_bit(&mut self, bit_offset: usize, value: bool);
141
142 /// Writes an integer to the container.
143 ///
144 /// # Arguments
145 ///
146 /// * `bit_offset`: Starting offset in the bit array.
147 /// * `value`: The integer to be written.
148 /// * `width`: The width of the integer in bits.
149 ///
150 /// # Safety
151 ///
152 /// Behavior is undefined if `width > 64`.
153 ///
154 /// # Panics
155 ///
156 /// May panic if `bit_offset + width - 1` is not a valid offset in the bit array.
157 /// May panic if the underlying data is not mutable.
158 /// May panic from I/O errors.
159 unsafe fn set_int(&mut self, bit_offset: usize, value: u64, width: usize);
160}
161
162//-----------------------------------------------------------------------------
163
164/// Append bits and variable-width integers to a container.
165///
166/// The container is not required to remember the types of the pushed items.
167///
168/// # Examples
169/// ```
170/// use simple_sds_sbwt::raw_vector::PushRaw;
171/// use simple_sds_sbwt::bits;
172///
173/// struct Example(Vec<bool>, Vec<u64>);
174///
175/// impl Example{
176/// fn new() -> Example {
177/// Example(Vec::new(), Vec::new())
178/// }
179/// }
180///
181/// impl PushRaw for Example {
182/// fn push_bit(&mut self, value: bool) {
183/// self.0.push(value);
184/// }
185///
186/// unsafe fn push_int(&mut self, value: u64, width: usize) {
187/// self.1.push(value & bits::low_set(width));
188/// }
189/// }
190///
191/// let mut example = Example::new();
192/// example.push_bit(false);
193/// unsafe {
194/// example.push_int(123, 8);
195/// example.push_int(456, 9);
196/// }
197/// example.push_bit(true);
198///
199/// assert_eq!(example.0.len(), 2);
200/// assert_eq!(example.1.len(), 2);
201/// ```
202pub trait PushRaw {
203 /// Appends a bit to the container.
204 ///
205 /// # Panics
206 ///
207 /// May panic from I/O errors.
208 /// May panic if there is an integer overflow.
209 fn push_bit(&mut self, value: bool);
210
211 /// Appends an integer to the container.
212 ///
213 /// # Arguments
214 ///
215 /// * `value`: The integer to be appended.
216 /// * `width`: The width of the integer in bits.
217 ///
218 /// # Safety
219 ///
220 /// Behavior is undefined if `width > 64`.
221 ///
222 /// # Panics
223 ///
224 /// May panic from I/O errors.
225 /// May panic if there is an integer overflow.
226 unsafe fn push_int(&mut self, value: u64, width: usize);
227}
228
229/// Remove and return bits and variable-width integers from a container.
230///
231/// Behavior is implementation-dependent if the sequence of pop operations is not the reverse of push operations.
232///
233/// # Examples
234/// ```
235/// use simple_sds_sbwt::raw_vector::PopRaw;
236///
237/// struct Example(Vec<bool>, Vec<u64>);
238///
239/// impl Example{
240/// fn new() -> Example {
241/// Example(Vec::new(), Vec::new())
242/// }
243/// }
244///
245/// impl PopRaw for Example {
246/// fn pop_bit(&mut self) -> Option<bool> {
247/// self.0.pop()
248/// }
249///
250/// unsafe fn pop_int(&mut self, _: usize) -> Option<u64> {
251/// self.1.pop()
252/// }
253/// }
254///
255/// let mut example = Example::new();
256/// example.0.push(false);
257/// example.1.push(123);
258/// example.1.push(456);
259/// example.0.push(true);
260///
261/// assert_eq!(example.pop_bit().unwrap(), true);
262/// unsafe {
263/// assert_eq!(example.pop_int(9).unwrap(), 456);
264/// assert_eq!(example.pop_int(8).unwrap(), 123);
265/// }
266/// assert_eq!(example.pop_bit().unwrap(), false);
267/// assert_eq!(example.pop_bit(), None);
268/// unsafe { assert_eq!(example.pop_int(1), None); }
269/// ```
270pub trait PopRaw {
271 /// Removes and returns the last bit from the container.
272 ///
273 /// Returns [`None`] the container does not have more bits.
274 fn pop_bit(&mut self) -> Option<bool>;
275
276 /// Removes and returns the last `width` bits from the container as an integer.
277 ///
278 /// Returns [`None`] if the container does not have more integers of that width.
279 ///
280 /// # Safety
281 ///
282 /// Behavior is undefined if `width > 64`.
283 unsafe fn pop_int(&mut self, width: usize) -> Option<u64>;
284}
285
286//-----------------------------------------------------------------------------
287
288/// A contiguous growable array of bits and up to 64-bit integers based on [`Vec`] of [`u64`] values.
289///
290/// There are no iterators over the vector, because it may contain items of varying widths.
291///
292/// # Notes
293///
294/// * The unused part of the last integer is always set to `0`.
295/// * The underlying vector may allocate but not use more integers than are strictly necessary.
296/// * `RawVector` never panics from I/O errors.
297#[derive(Clone, Debug, PartialEq, Eq, Default)]
298pub struct RawVector {
299 len: usize,
300 data: Vec<u64>,
301}
302
303impl RawVector {
304 /// Returns the length of the vector in bits.
305 #[inline]
306 pub fn len(&self) -> usize {
307 self.len
308 }
309
310 /// Returns `true` if the vector is empty.
311 #[inline]
312 pub fn is_empty(&self) -> bool {
313 self.len() == 0
314 }
315
316 /// Returns the capacity of the vector in bits.
317 #[inline]
318 pub fn capacity(&self) -> usize {
319 bits::words_to_bits(self.data.capacity())
320 }
321
322 /// Counts the number of ones in the bit array.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// use simple_sds_sbwt::raw_vector::{RawVector, AccessRaw};
328 ///
329 /// let mut v = RawVector::with_len(137, false);
330 /// assert_eq!(v.count_ones(), 0);
331 /// v.set_bit(1, true); v.set_bit(33, true); v.set_bit(95, true); v.set_bit(123, true);
332 /// assert_eq!(v.count_ones(), 4);
333 /// ```
334 pub fn count_ones(&self) -> usize {
335 let mut result: usize = 0;
336 for value in self.data.iter() {
337 result += (*value).count_ones() as usize;
338 }
339 result
340 }
341
342 /// Creates an empty vector.
343 ///
344 /// # Examples
345 ///
346 /// ```
347 /// use simple_sds_sbwt::raw_vector::RawVector;
348 ///
349 /// let v = RawVector::new();
350 /// assert!(v.is_empty());
351 /// assert_eq!(v.capacity(), 0);
352 /// ```
353 pub fn new() -> RawVector {
354 RawVector::default()
355 }
356
357 /// Creates an initialized vector of specified length.
358 ///
359 /// # Arguments
360 ///
361 /// * `len`: Length of the vector in bits.
362 /// * `value`: Initialization value.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use simple_sds_sbwt::raw_vector::RawVector;
368 ///
369 /// let v = RawVector::with_len(137, false);
370 /// assert_eq!(v.len(), 137);
371 /// ```
372 pub fn with_len(len: usize, value: bool) -> RawVector {
373 let val = bits::filler_value(value);
374 let data: Vec<u64> = vec![val; bits::bits_to_words(len)];
375 let mut result = RawVector {
376 len, data,
377 };
378 result.set_unused_bits(false);
379 result
380 }
381
382 /// Creates an empty vector with enough capacity for at least `capacity` bits.
383 ///
384 /// # Examples
385 ///
386 /// ```
387 /// use simple_sds_sbwt::raw_vector::RawVector;
388 ///
389 /// let v = RawVector::with_capacity(137);
390 /// assert!(v.capacity() >= 137);
391 /// ```
392 pub fn with_capacity(capacity: usize) -> RawVector {
393 RawVector {
394 len: 0,
395 data: Vec::with_capacity(bits::bits_to_words(capacity)),
396 }
397 }
398
399 /// Returns the size of a serialized vector with the given capacity in [`u64`] elements.
400 ///
401 /// # Examples
402 ///
403 /// ```
404 /// use simple_sds_sbwt::raw_vector::RawVector;
405 ///
406 /// assert_eq!(RawVector::size_by_params(247), 6);
407 /// ```
408 pub fn size_by_params(capacity: usize) -> usize {
409 2 + bits::bits_to_words(capacity)
410 }
411
412 /// Returns a copy of the vector with each bit flipped.
413 ///
414 /// # Examples
415 ///
416 /// ```
417 /// use simple_sds_sbwt::raw_vector::{RawVector, AccessRaw};
418 ///
419 /// let mut original = RawVector::with_len(137, false);
420 /// original.set_bit(1, true); original.set_bit(33, true);
421 /// unsafe { original.set_int(95, 456, 9); } original.set_bit(123, true);
422 /// let complement = original.complement();
423 /// for i in 0..137 {
424 /// assert_eq!(!(complement.bit(i)), original.bit(i));
425 /// }
426 /// ```
427 pub fn complement(&self) -> RawVector {
428 let mut result = self.clone();
429 for word in result.data.iter_mut() {
430 *word = !*word;
431 }
432 result.set_unused_bits(false);
433 result
434 }
435
436 /// Resizes the vector to a specified length.
437 ///
438 /// If `new_len > self.len()`, the new `new_len - self.len()` bits will be initialized.
439 /// If `new_len < self.len()`, the vector is truncated.
440 ///
441 /// # Arguments
442 ///
443 /// * `new_len`: New length of the vector in bits.
444 /// * `value`: Initialization value.
445 ///
446 /// # Examples
447 ///
448 /// ```
449 /// use simple_sds_sbwt::raw_vector::RawVector;
450 ///
451 /// let mut v = RawVector::new();
452 /// v.resize(137, true);
453 /// let w = RawVector::with_len(137, true);
454 /// assert_eq!(v, w);
455 /// ```
456 pub fn resize(&mut self, new_len: usize, value: bool) {
457 // Fill the unused bits if necessary.
458 if new_len > self.len() {
459 self.set_unused_bits(value);
460 }
461
462 // Use more space if necessary.
463 self.data.resize(bits::bits_to_words(new_len), bits::filler_value(value));
464 self.len = new_len;
465 self.set_unused_bits(false);
466 }
467
468 /// Clears the vector without freeing the data.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// use simple_sds_sbwt::raw_vector::RawVector;
474 ///
475 /// let mut v = RawVector::with_len(137, true);
476 /// assert_eq!(v.len(), 137);
477 /// v.clear();
478 /// assert!(v.is_empty());
479 /// ```
480 pub fn clear(&mut self) {
481 self.data.clear();
482 self.len = 0;
483 }
484
485 /// Reserves space for storing at least `self.len() + additional` bits in the vector.
486 ///
487 /// Does nothing if the capacity is already sufficient.
488 ///
489 /// # Examples
490 ///
491 /// ```
492 /// use simple_sds_sbwt::raw_vector::RawVector;
493 ///
494 /// let mut v = RawVector::with_len(137, false);
495 /// v.reserve(318);
496 /// assert!(v.capacity() >= 137 + 318);
497 /// ```
498 ///
499 /// # Panics
500 ///
501 /// May panic if `self.len() + additional + 63 > usize::MAX`.
502 pub fn reserve(&mut self, additional: usize) {
503 let words_needed = bits::bits_to_words(self.len() + additional);
504 if words_needed > self.data.capacity() {
505 self.data.reserve(words_needed - self.data.capacity());
506 }
507 }
508
509 // Set the unused bits in the last integer to the specified value.
510 fn set_unused_bits(&mut self, value: bool) {
511 let (index, width) = bits::split_offset(self.len());
512 if width > 0 {
513 if value {
514 self.data[index] |= !bits::low_set(width);
515 }
516 else {
517 self.data[index] &= bits::low_set(width);
518 }
519 }
520 }
521
522
523 pub fn get_words(&self) -> &[u64] {
524 &self.data
525 }
526
527 // Returns the underlying words and the length of the bit vector in bits. The
528 // last word may have padding bits past the end.
529 pub fn into_parts(self) -> (Vec<u64>, usize) {
530 (self.data, self.len)
531 }
532
533}
534
535//-----------------------------------------------------------------------------
536
537impl AccessRaw for RawVector {
538 #[inline]
539 fn bit(&self, bit_offset: usize) -> bool {
540 let (index, offset) = bits::split_offset(bit_offset);
541 ((self.data[index] >> offset) & 1) == 1
542 }
543
544 #[inline]
545 unsafe fn int(&self, bit_offset: usize, width: usize) -> u64 {
546 bits::read_int(&self.data, bit_offset, width)
547 }
548
549 #[inline]
550 fn word(&self, index: usize) -> u64 {
551 self.data[index]
552 }
553
554 #[inline]
555 unsafe fn word_unchecked(&self, index: usize) -> u64 {
556 *self.data.get_unchecked(index)
557 }
558
559 #[inline]
560 fn is_mutable(&self) -> bool {
561 true
562 }
563
564 #[inline]
565 fn set_bit(&mut self, bit_offset: usize, value: bool) {
566 let (index, offset) = bits::split_offset(bit_offset);
567 self.data[index] &= !(1u64 << offset);
568 self.data[index] |= (value as u64) << offset;
569 }
570
571 #[inline]
572 unsafe fn set_int(&mut self, bit_offset: usize, value: u64, width: usize) {
573 bits::write_int(&mut self.data, bit_offset, value, width);
574 }
575}
576
577impl PushRaw for RawVector {
578 fn push_bit(&mut self, value: bool) {
579 let (index, offset) = bits::split_offset(self.len);
580 if index == self.data.len() {
581 self.data.push(0);
582 }
583 self.data[index] |= (value as u64) << offset;
584 self.len += 1;
585 }
586
587 unsafe fn push_int(&mut self, value: u64, width: usize) {
588 if self.len + width > bits::words_to_bits(self.data.len()) {
589 self.data.push(0);
590 }
591 bits::write_int(&mut self.data, self.len, value, width);
592 self.len += width;
593 }
594}
595
596impl PopRaw for RawVector {
597 fn pop_bit(&mut self) -> Option<bool> {
598 if !self.is_empty() {
599 let result = self.bit(self.len - 1);
600 self.len -= 1;
601 self.data.resize(bits::bits_to_words(self.len()), 0); // Avoid using unnecessary words.
602 self.set_unused_bits(false);
603 Some(result)
604 } else {
605 None
606 }
607 }
608
609 unsafe fn pop_int(&mut self, width: usize) -> Option<u64> {
610 if self.len() >= width {
611 let result = self.int(self.len - width, width);
612 self.len -= width;
613 self.data.resize(bits::bits_to_words(self.len()), 0); // Avoid using unnecessary words.
614 self.set_unused_bits(false);
615 Some(result)
616 } else {
617 None
618 }
619 }
620}
621
622impl Serialize for RawVector {
623 fn serialize_header<T: io::Write>(&self, writer: &mut T) -> io::Result<()> {
624 self.len.serialize(writer)?;
625 self.data.serialize_header(writer)?;
626 Ok(())
627 }
628
629 fn serialize_body<T: io::Write>(&self, writer: &mut T) -> io::Result<()> {
630 self.data.serialize_body(writer)?;
631 Ok(())
632 }
633
634 fn load<T: io::Read>(reader: &mut T) -> io::Result<Self> {
635 let len = usize::load(reader)?;
636 let data = <Vec<u64> as Serialize>::load(reader)?;
637 if bits::bits_to_words(len) != data.len() {
638 Err(Error::new(ErrorKind::InvalidData, "Bit length / word length mismatch"))
639 } else {
640 Ok(RawVector {
641 len, data,
642 })
643 }
644 }
645
646 fn size_in_elements(&self) -> usize {
647 self.len.size_in_elements() + self.data.size_in_elements()
648 }
649}
650
651//-----------------------------------------------------------------------------
652
653impl AsRef<[u64]> for RawVector {
654 #[inline]
655 fn as_ref(&self) -> &[u64] {
656 self.data.as_ref()
657 }
658}
659
660//-----------------------------------------------------------------------------
661
662/// A buffered file writer compatible with the serialization format of [`RawVector`].
663///
664/// When the writer goes out of scope, the internal buffer is flushed, the file is closed, and all errors are ignored.
665/// Call [`RawVectorWriter::close`] explicitly to handle the errors.
666///
667/// # Examples
668///
669/// ```
670/// use simple_sds_sbwt::raw_vector::{RawVector, RawVectorWriter, AccessRaw, PushRaw};
671/// use simple_sds_sbwt::serialize;
672/// use std::fs;
673///
674/// let filename = serialize::temp_file_name("raw-vector-writer");
675/// let width = 29;
676/// let mut header: Vec<u64> = Vec::new();
677/// let mut writer = RawVectorWriter::new(&filename, &mut header).unwrap();
678/// unsafe {
679/// writer.push_int(123, width);
680/// writer.push_int(456, width);
681/// writer.push_int(789, width);
682/// }
683/// writer.close();
684///
685/// let v: RawVector = serialize::load_from(&filename).unwrap();
686/// assert_eq!(v.len(), 3 * width);
687/// unsafe {
688/// assert_eq!(v.int(0, width), 123);
689/// assert_eq!(v.int(width, width), 456);
690/// assert_eq!(v.int(2 * width, width), 789);
691/// }
692///
693/// fs::remove_file(&filename);
694/// ```
695#[derive(Debug)]
696pub struct RawVectorWriter {
697 len: usize,
698 buf_len: usize,
699 buf: RawVector,
700 file: Option<File>,
701 filename: PathBuf,
702}
703
704// Ways of flushing a write buffer.
705#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
706enum FlushMode {
707 // Only flush the part of the buffer that can be flushed safely.
708 Safe,
709 // Flush the entire buffer.
710 // Subsequent writes to the buffer may leave it in an invalid state.
711 Final,
712}
713
714impl RawVectorWriter {
715 /// Default buffer size in bits.
716 pub const DEFAULT_BUFFER_SIZE: usize = 8 * 1024 * 1024;
717
718 /// Returns the length of the vector in bits.
719 #[inline]
720 pub fn len(&self) -> usize {
721 self.len
722 }
723
724 /// Returns `true` if the vector is empty.
725 #[inline]
726 pub fn is_empty(&self) -> bool {
727 self.len() == 0
728 }
729
730 /// Creates an empty vector stored in the specified file with the default buffer size.
731 ///
732 /// If the file already exists, it will be overwritten.
733 ///
734 /// # Arguments
735 ///
736 /// * `filename`: Name of the file.
737 /// * `header`: Header of the parent structure (may be empty).
738 pub fn new<P: AsRef<Path>>(filename: P, header: &mut Vec<u64>) -> io::Result<RawVectorWriter> {
739 let mut options = OpenOptions::new();
740 let file = options.create(true).write(true).truncate(true).open(&filename)?;
741 // Allocate one extra word for overflow.
742 let buf = RawVector::with_capacity(Self::DEFAULT_BUFFER_SIZE + bits::WORD_BITS);
743 let mut name = PathBuf::new();
744 name.push(&filename);
745 let mut result = RawVectorWriter {
746 len: 0,
747 buf_len: Self::DEFAULT_BUFFER_SIZE,
748 buf,
749 file: Some(file),
750 filename: name,
751 };
752 result.write_header(header)?;
753 Ok(result)
754 }
755
756 /// Creates an empty vector stored in the specified file with user-defined buffer size.
757 ///
758 /// If the file already exists, it will be overwritten.
759 /// The buffer size will be rounded up to the next multiple of [`bits::WORD_BITS`].
760 ///
761 /// # Arguments
762 ///
763 /// * `filename`: Name of the file.
764 /// * `header`: Header of the parent structure (may be empty).
765 /// * `buf_len`: Buffer size in bits.
766 pub fn with_buf_len<P: AsRef<Path>>(filename: P, header: &mut Vec<u64>, buf_len: usize) -> io::Result<RawVectorWriter> {
767 // Buffer length must be a positive multiple of `bits::WORD_BITS`.
768 let buf_len = cmp::max(bits::round_up_to_word_bits(buf_len), bits::WORD_BITS);
769 let mut options = OpenOptions::new();
770 let file = options.create(true).write(true).truncate(true).open(&filename)?;
771 // Allocate one extra word for overflow.
772 let buf = RawVector::with_capacity(buf_len + bits::WORD_BITS);
773 let mut name = PathBuf::new();
774 name.push(&filename);
775 let mut result = RawVectorWriter {
776 len: 0,
777 buf_len,
778 buf,
779 file: Some(file),
780 filename: name,
781 };
782 result.write_header(header)?;
783 Ok(result)
784 }
785
786 /// Returns the name of the file.
787 pub fn filename(&self) -> &Path {
788 self.filename.as_path()
789 }
790
791 /// Returns `true` if the file is open for writing.
792 pub fn is_open(&self) -> bool {
793 self.file.is_some()
794 }
795
796 // Flushes the buffer.
797 fn flush(&mut self, mode: FlushMode) -> io::Result<()> {
798 if let Some(f) = self.file.as_mut() {
799 // Handle the overflow if not serializing the entire buffer.
800 let mut overflow: (u64, usize) = (0, 0);
801 if let FlushMode::Safe = mode {
802 if self.buf.len() > self.buf_len {
803 unsafe { overflow = (self.buf.int(self.buf_len, self.buf.len() - self.buf_len), self.buf.len() - self.buf_len); }
804 self.buf.resize(self.buf_len, false);
805 }
806 }
807
808 // Serialize and clear the buffer.
809 self.buf.serialize_body(f)?;
810 self.buf.clear();
811
812 // Push the overflow back to the buffer.
813 if let FlushMode::Safe = mode {
814 if overflow.1 > 0 {
815 unsafe { self.buf.push_int(overflow.0, overflow.1); }
816 }
817 }
818 }
819 Ok(())
820 }
821
822 // Seeks to the start of the file, appends its own header to `header`, and writes it into the file.
823 fn write_header(&mut self, header: &mut Vec<u64>) -> io::Result<()> {
824 if let Some(f) = self.file.as_mut() {
825 f.seek(SeekFrom::Start(0))?;
826 header.push(self.len as u64);
827 header.push(bits::bits_to_words(self.len) as u64);
828 header.serialize_body(f)?;
829 }
830 Ok(())
831 }
832
833 /// Flushes the buffer, writes the header, and closes the file.
834 ///
835 /// No effect if the file is closed.
836 ///
837 /// # Errors
838 ///
839 /// Any I/O errors will be passed through.
840 pub fn close(&mut self) -> io::Result<()> {
841 let mut header: Vec<u64> = Vec::new();
842 self.close_with_header(&mut header)
843 }
844
845 /// Flushes the buffer, writes the header, and closes the file.
846 ///
847 /// No effect if the file is closed.
848 /// This method should only be called by the `close` method of a parent writer.
849 ///
850 /// # Errors
851 ///
852 /// Any I/O errors will be passed through.
853 pub fn close_with_header(&mut self, header: &mut Vec<u64>) -> io::Result<()> {
854 if self.is_open() {
855 self.flush(FlushMode::Final)?;
856 self.write_header(header)?;
857 self.file = None
858 }
859 Ok(())
860 }
861}
862
863//-----------------------------------------------------------------------------
864
865impl PushRaw for RawVectorWriter {
866 fn push_bit(&mut self, value: bool) {
867 self.buf.push_bit(value); self.len += 1;
868 if self.buf.len() >= self.buf_len {
869 self.flush(FlushMode::Safe).unwrap();
870 }
871 }
872
873 unsafe fn push_int(&mut self, value: u64, width: usize) {
874 self.buf.push_int(value, width); self.len += width;
875 if self.buf.len() >= self.buf_len {
876 self.flush(FlushMode::Safe).unwrap();
877 }
878 }
879}
880
881impl Drop for RawVectorWriter {
882 fn drop(&mut self) {
883 let _ = self.close();
884 }
885}
886
887//-----------------------------------------------------------------------------
888
889/// An immutable memory-mapped [`RawVector`].
890///
891/// This is compatible with the serialization format of [`RawVector`].
892///
893/// # Examples
894///
895/// ```
896/// use simple_sds_sbwt::raw_vector::{RawVector, RawVectorMapper, AccessRaw, PushRaw};
897/// use simple_sds_sbwt::serialize::{MemoryMap, MemoryMapped, MappingMode};
898/// use simple_sds_sbwt::serialize;
899/// use std::fs;
900///
901/// let filename = serialize::temp_file_name("raw-vector-mapper");
902/// let width = 29;
903/// let mut original = RawVector::new();
904/// unsafe {
905/// original.push_int(123, width);
906/// original.push_int(456, width);
907/// original.push_int(789, width);
908/// }
909/// serialize::serialize_to(&original, &filename);
910///
911/// let map = MemoryMap::new(&filename, MappingMode::ReadOnly).unwrap();
912/// let mapper = RawVectorMapper::new(&map, 0).unwrap();
913/// assert_eq!(mapper.len(), 3 * width);
914/// unsafe {
915/// assert_eq!(mapper.int(0, width), 123);
916/// assert_eq!(mapper.int(width, width), 456);
917/// assert_eq!(mapper.int(2 * width, width), 789);
918/// }
919///
920/// drop(mapper); drop(map);
921/// fs::remove_file(&filename);
922/// ```
923#[cfg(not(target_family = "wasm"))]
924#[derive(PartialEq, Eq, Debug)]
925pub struct RawVectorMapper<'a> {
926 len: usize,
927 data: MappedSlice<'a, u64>,
928}
929
930#[cfg(not(target_family = "wasm"))]
931impl<'a> RawVectorMapper<'a> {
932 /// Returns the length of the vector in bits.
933 #[inline]
934 pub fn len(&self) -> usize {
935 self.len
936 }
937
938 /// Returns `true` if the vector is empty.
939 #[inline]
940 pub fn is_empty(&self) -> bool {
941 self.len() == 0
942 }
943
944 /// Counts the number of ones in the bit array.
945 pub fn count_ones(&self) -> usize {
946 let mut result: usize = 0;
947 for value in self.data.iter() {
948 result += (*value).count_ones() as usize;
949 }
950 result
951 }
952}
953
954#[cfg(not(target_family = "wasm"))]
955impl<'a> AccessRaw for RawVectorMapper<'a> {
956 #[inline]
957 fn bit(&self, bit_offset: usize) -> bool {
958 let (index, offset) = bits::split_offset(bit_offset);
959 ((self.data[index] >> offset) & 1) == 1
960 }
961
962 #[inline]
963 unsafe fn int(&self, bit_offset: usize, width: usize) -> u64 {
964 bits::read_int(&self.data, bit_offset, width)
965 }
966
967 #[inline]
968 fn word(&self, index: usize) -> u64 {
969 self.data[index]
970 }
971
972 #[inline]
973 unsafe fn word_unchecked(&self, index: usize) -> u64 {
974 *self.data.get_unchecked(index)
975 }
976
977 #[inline]
978 fn is_mutable(&self) -> bool {
979 false
980 }
981
982 #[inline]
983 fn set_bit(&mut self, _: usize, _: bool) {
984 panic!("RawVectorMapper::set_bit(): Not implemented");
985 }
986
987 #[inline]
988 unsafe fn set_int(&mut self, _: usize, _: u64, _: usize) {
989 panic!("RawVectorMapper::set_int(): Not implemented");
990 }
991}
992
993#[cfg(not(target_family = "wasm"))]
994impl<'a> MemoryMapped<'a> for RawVectorMapper<'a> {
995 fn new(map: &'a MemoryMap, offset: usize) -> io::Result<Self> {
996 if offset >= map.len() {
997 return Err(Error::new(ErrorKind::UnexpectedEof, "The starting offset is out of range"));
998 }
999 let slice: &[u64] = map.as_ref();
1000 let len = slice[offset] as usize;
1001 let data = MappedSlice::new(map, offset + 1)?;
1002 Ok(RawVectorMapper {
1003 len, data,
1004 })
1005 }
1006
1007 fn map_offset(&self) -> usize {
1008 self.data.map_offset() - 1
1009 }
1010
1011 fn map_len(&self) -> usize {
1012 self.data.map_len() + 1
1013 }
1014}
1015
1016#[cfg(not(target_family = "wasm"))]
1017impl<'a> AsRef<MappedSlice<'a, u64>> for RawVectorMapper<'a> {
1018 #[inline]
1019 fn as_ref(&self) -> &MappedSlice<'a, u64> {
1020 &(self.data)
1021 }
1022}
1023
1024//-----------------------------------------------------------------------------