binseq 0.10.0

A high efficiency binary format for sequencing data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use crate::{BitSize, Result, error::WriteError};

/// A zero-copy (borrowed) record used to write sequences to any BINSEQ format.
///
/// # Example
///
/// ```
/// use binseq::SequencingRecordBuilder;
///
/// let record = SequencingRecordBuilder::default()
///     .s_seq(b"ACGTACGT")
///     .s_qual(b"IIIIFFFF")
///     .s_header(b"seq_001")
///     .flag(42)
///     .build()
///     .unwrap();
/// ```
#[derive(Clone, Copy, Default)]
pub struct SequencingRecord<'a> {
    pub s_seq: &'a [u8],
    pub s_qual: Option<&'a [u8]>,
    pub s_header: Option<&'a [u8]>,
    pub x_seq: Option<&'a [u8]>,
    pub x_qual: Option<&'a [u8]>,
    pub x_header: Option<&'a [u8]>,
    pub flag: Option<u64>,
}

impl<'a> SequencingRecord<'a> {
    #[inline]
    #[must_use]
    pub fn new(
        s_seq: &'a [u8],
        s_qual: Option<&'a [u8]>,
        s_header: Option<&'a [u8]>,
        x_seq: Option<&'a [u8]>,
        x_qual: Option<&'a [u8]>,
        x_header: Option<&'a [u8]>,
        flag: Option<u64>,
    ) -> Self {
        Self {
            s_seq,
            s_qual,
            s_header,
            x_seq,
            x_qual,
            x_header,
            flag,
        }
    }

    /// Returns the encoded size of this record for CBQ, given the writer configuration.
    ///
    /// Extra data the writer won't use is not counted.
    #[inline]
    #[must_use]
    pub fn configured_size_cbq(
        &self,
        is_paired: bool,
        has_flags: bool,
        has_headers: bool,
        has_qualities: bool,
    ) -> usize {
        // CBQ uses 2-bit encoding: 4 nucleotides per byte, 32 per u64 word
        const NUCS_PER_WORD: usize = 32;

        let mut size = 0;

        // Sequence size (encoded into u64 words)
        let s_chunks = self.s_seq.len().div_ceil(NUCS_PER_WORD);
        size += s_chunks * 8;

        // Extended sequence (only if writer is configured for paired)
        if is_paired {
            let x_chunks = self.x_seq.map_or(0, |x| x.len().div_ceil(NUCS_PER_WORD));
            size += x_chunks * 8;
        }

        // Flag size (only if writer is configured for flags)
        if has_flags {
            size += 8; // u64
        }

        // Header size (only if writer is configured for headers)
        if has_headers {
            size += self.s_header.map_or(0, <[u8]>::len);
            if is_paired {
                size += self.x_header.map_or(0, <[u8]>::len);
            }
        }

        // Quality size (only if writer is configured for qualities)
        if has_qualities {
            size += self.s_qual.map_or(0, <[u8]>::len);
            if is_paired {
                size += self.x_qual.map_or(0, <[u8]>::len);
            }
        }

        size
    }

    /// Returns the encoded size of this record for VBQ (row-based, length-prefixed),
    /// given the writer configuration.
    ///
    /// Extra data the writer won't use is not counted.
    /// See [`vbq`](crate::vbq) for the record layout.
    #[inline]
    #[must_use]
    pub fn configured_size_vbq(
        &self,
        is_paired: bool,
        has_flags: bool,
        has_headers: bool,
        has_qualities: bool,
        bitsize: BitSize,
    ) -> usize {
        // Calculate how many nucleotides fit per byte for the given bitsize
        let nucs_per_byte = if matches!(bitsize, BitSize::Two) {
            4
        } else {
            2
        };
        // VBQ packs sequences into u64 words
        let nucs_per_word = nucs_per_byte * 8;

        let mut size = 0;

        // Length prefixes: s_len and x_len (always present)
        size += 16; // 2 * u64

        // Flag (8 bytes, if has_flags)
        if has_flags {
            size += 8;
        }

        // Primary sequence (encoded into u64 words)
        let s_chunks = self.s_seq.len().div_ceil(nucs_per_word);
        size += s_chunks * 8;

        // Extended sequence (only if writer is configured for paired)
        if is_paired {
            let x_chunks = self.x_seq.map_or(0, |x| x.len().div_ceil(nucs_per_word));
            size += x_chunks * 8;
        }

        // Quality scores (raw bytes, only if writer configured for qualities)
        if has_qualities {
            size += self.s_qual.map_or(0, <[u8]>::len);
            if is_paired {
                size += self.x_qual.map_or(0, <[u8]>::len);
            }
        }

        // Headers (length prefix + raw bytes, only if writer configured for headers)
        if has_headers {
            if let Some(h) = self.s_header {
                size += 8 + h.len(); // length prefix + header bytes
            }
            if is_paired && let Some(h) = self.x_header {
                size += 8 + h.len(); // length prefix + header bytes
            }
        }

        size
    }

    #[inline]
    #[must_use]
    pub fn is_paired(&self) -> bool {
        self.x_seq.is_some()
    }

    #[inline]
    #[must_use]
    pub fn has_flags(&self) -> bool {
        self.flag.is_some()
    }

    #[inline]
    #[must_use]
    pub fn has_headers(&self) -> bool {
        self.s_header.is_some() || self.x_header.is_some()
    }

    #[inline]
    #[must_use]
    pub fn has_qualities(&self) -> bool {
        self.s_qual.is_some() || self.x_qual.is_some()
    }
}

/// Builder for a [`SequencingRecord`]
///
/// # Example
///
/// ```
/// use binseq::SequencingRecordBuilder;
///
/// // Build a simple unpaired record
/// let record = SequencingRecordBuilder::default()
///     .s_seq(b"ACGTACGT")
///     .build()
///     .unwrap();
///
/// // Build a paired record with quality scores
/// let paired = SequencingRecordBuilder::default()
///     .s_seq(b"ACGTACGT")
///     .s_qual(b"IIIIFFFF")
///     .x_seq(b"TGCATGCA")
///     .x_qual(b"FFFFHHHH")
///     .flag(1)
///     .build()
///     .unwrap();
/// ```
#[derive(Default)]
pub struct SequencingRecordBuilder<'a> {
    s_seq: Option<&'a [u8]>,
    s_qual: Option<&'a [u8]>,
    s_header: Option<&'a [u8]>,
    x_seq: Option<&'a [u8]>,
    x_qual: Option<&'a [u8]>,
    x_header: Option<&'a [u8]>,
    flag: Option<u64>,
}

impl<'a> SequencingRecordBuilder<'a> {
    /// Sets the primary sequence (required)
    #[must_use]
    pub fn s_seq(mut self, s_seq: &'a [u8]) -> Self {
        self.s_seq = Some(s_seq);
        self
    }

    /// Sets the primary quality scores
    #[must_use]
    pub fn s_qual(mut self, s_qual: &'a [u8]) -> Self {
        self.s_qual = Some(s_qual);
        self
    }

    /// Sets the primary quality scores from an Option
    #[must_use]
    pub fn opt_s_qual(mut self, s_qual: Option<&'a [u8]>) -> Self {
        self.s_qual = s_qual;
        self
    }

    /// Sets the primary header
    #[must_use]
    pub fn s_header(mut self, s_header: &'a [u8]) -> Self {
        self.s_header = Some(s_header);
        self
    }

    /// Sets the primary header from an Option
    #[must_use]
    pub fn opt_s_header(mut self, s_header: Option<&'a [u8]>) -> Self {
        self.s_header = s_header;
        self
    }

    /// Sets the extended/paired sequence
    #[must_use]
    pub fn x_seq(mut self, x_seq: &'a [u8]) -> Self {
        self.x_seq = Some(x_seq);
        self
    }

    /// Sets the extended/paired sequence from an Option
    #[must_use]
    pub fn opt_x_seq(mut self, x_seq: Option<&'a [u8]>) -> Self {
        self.x_seq = x_seq;
        self
    }

    /// Sets the extended quality scores
    #[must_use]
    pub fn x_qual(mut self, x_qual: &'a [u8]) -> Self {
        self.x_qual = Some(x_qual);
        self
    }

    /// Sets the extended quality scores from an Option
    #[must_use]
    pub fn opt_x_qual(mut self, x_qual: Option<&'a [u8]>) -> Self {
        self.x_qual = x_qual;
        self
    }

    /// Sets the extended header
    #[must_use]
    pub fn x_header(mut self, x_header: &'a [u8]) -> Self {
        self.x_header = Some(x_header);
        self
    }

    /// Sets the extended header from an Option
    #[must_use]
    pub fn opt_x_header(mut self, x_header: Option<&'a [u8]>) -> Self {
        self.x_header = x_header;
        self
    }

    /// Sets the flag value
    #[must_use]
    pub fn flag(mut self, flag: u64) -> Self {
        self.flag = Some(flag);
        self
    }

    /// Sets the flag value from an Option
    #[must_use]
    pub fn opt_flag(mut self, flag: Option<u64>) -> Self {
        self.flag = flag;
        self
    }

    /// Builds the `SequencingRecord`; errors if `s_seq` is not set
    pub fn build(self) -> Result<SequencingRecord<'a>> {
        let Some(s_seq) = self.s_seq else {
            return Err(WriteError::MissingSequence.into());
        };
        Ok(SequencingRecord {
            s_seq,
            s_qual: self.s_qual,
            s_header: self.s_header,
            x_seq: self.x_seq,
            x_qual: self.x_qual,
            x_header: self.x_header,
            flag: self.flag,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ==================== SequencingRecord::new() and accessors ====================

    #[test]
    fn test_new_constructor() {
        let record = SequencingRecord::new(
            b"ACGT",
            Some(b"IIII"),
            Some(b"s_hdr"),
            Some(b"TGCA"),
            Some(b"FFFF"),
            Some(b"x_hdr"),
            Some(7),
        );
        assert_eq!(record.s_seq, b"ACGT");
        assert_eq!(record.s_qual, Some(b"IIII".as_slice()));
        assert_eq!(record.s_header, Some(b"s_hdr".as_slice()));
        assert_eq!(record.x_seq, Some(b"TGCA".as_slice()));
        assert_eq!(record.x_qual, Some(b"FFFF".as_slice()));
        assert_eq!(record.x_header, Some(b"x_hdr".as_slice()));
        assert_eq!(record.flag, Some(7));
    }

    #[test]
    fn test_new_constructor_minimal() {
        let record = SequencingRecord::new(b"ACGT", None, None, None, None, None, None);
        assert_eq!(record.s_seq, b"ACGT");
        assert_eq!(record.s_qual, None);
        assert_eq!(record.s_header, None);
        assert_eq!(record.x_seq, None);
        assert_eq!(record.x_qual, None);
        assert_eq!(record.x_header, None);
        assert_eq!(record.flag, None);
        assert!(!record.is_paired());
        assert!(!record.has_flags());
        assert!(!record.has_headers());
        assert!(!record.has_qualities());
    }

    // ==================== SequencingRecordBuilder opt_* setters ====================

    #[test]
    fn test_builder_opt_setters() {
        let record = SequencingRecordBuilder::default()
            .s_seq(b"ACGT")
            .opt_s_qual(Some(b"FFFF"))
            .opt_s_header(Some(b"s_hdr"))
            .opt_x_seq(Some(b"TGCA"))
            .opt_x_qual(None)
            .opt_x_header(None)
            .opt_flag(Some(42))
            .build()
            .unwrap();
        // field access and getters are equivalent
        assert_eq!(record.s_qual, Some(b"FFFF".as_slice()));
        assert_eq!(record.s_header, Some(b"s_hdr".as_slice()));
        assert_eq!(record.x_seq, Some(b"TGCA".as_slice()));
        assert_eq!(record.x_qual, None);
        assert_eq!(record.x_header, None);
        assert_eq!(record.flag, Some(42));
    }

    #[test]
    fn test_builder_missing_sequence() {
        let result = SequencingRecordBuilder::default().build();
        assert!(result.is_err());
    }
}