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
//! # bitnuc
//!
//! A library for efficient nucleotide sequence manipulation using 2-bit encoding.
//!
//! ## Features
//!
//! - 2-bit nucleotide encoding (A=00, C=01, G=10, T=11)
//! - 4-bit nucleotide encoding (A=0000, C=0001, G=0010, T=0011, N=1111)
//! - Direct bit manipulation functions for custom implementations
//! - Higher-level sequence type with additional analysis features
//!
//! ## Low-Level Packing Functions
//!
//! For direct bit manipulation, use the `as_2bit` and `from_2bit` functions:
//!
//! ```rust
//! use bitnuc::{as_2bit, from_2bit, from_2bit_alloc};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Pack a sequence into a u64
//! let packed = as_2bit(b"ACGT")?;
//! assert_eq!(packed, 0b11100100);
//!
//! // Unpack back to a sequence using a reusable buffer
//! let mut unpacked = Vec::new();
//! from_2bit(packed, 4, &mut unpacked)?;
//! assert_eq!(&unpacked, b"ACGT");
//! unpacked.clear();
//!
//! // Unpack back to a sequence with a reallocation
//! let unpacked = from_2bit_alloc(packed, 4)?;
//! assert_eq!(&unpacked, b"ACGT");
//!
//! Ok(())
//! }
//! ```
//!
//! These functions are useful when you need to:
//! - Implement custom sequence storage
//! - Manipulate sequences at the bit level
//! - Integrate with other bioinformatics tools
//! - Copy sequences more efficiently
//! - Hash sequences more efficiently
//!
//! For example, packing multiple short sequences:
//!
//! ```rust
//! use bitnuc::{as_2bit, from_2bit};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Pack multiple 4-mers into u64s
//! let kmers = [b"ACGT", b"TGCA", b"GGCC"];
//! let packed: Vec<u64> = kmers
//! .into_iter()
//! .map(|kmer| as_2bit(kmer))
//! .collect::<Result<_, _>>()?;
//!
//! // Unpack when needed
//! let mut unpacked = Vec::new();
//! from_2bit(packed[0], 4, &mut unpacked)?;
//! assert_eq!(&unpacked, b"ACGT");
//! Ok(())
//! }
//! ```
//!
//! ## Mid-Level Encoding Functions
//!
//! For more control over encoding and decoding, use the `encode` and `decode` functions:
//!
//! These will handle sequences of any length, padding the last u64 with zeros if needed.
//!
//! We'll use the [`nucgen`](https://crates.io/crates/nucgen) crate to generate random sequences for testing:
//!
//! ```rust
//! use bitnuc::twobit::{encode, decode};
//! use nucgen::Sequence;
//!
//! let mut rng = rand::thread_rng();
//! let mut seq = Sequence::new();
//! let seq_len = 1000;
//!
//! // Generate a random sequence
//! seq.fill_buffer(&mut rng, seq_len);
//!
//! // Encode the sequence
//! let mut ebuf = Vec::new(); // Buffer for encoded sequence
//! encode(seq.bytes(), &mut ebuf);
//!
//! // Decode the sequence
//! let mut dbuf = Vec::new(); // Buffer for decoded sequence
//! decode(&ebuf, seq_len, &mut dbuf);
//!
//! // Check that the decoded sequence matches the original
//! assert_eq!(seq.bytes(), &dbuf);
//! ```
//!
//! Note that the `encode` function will always encode a full u64.
//! If you have a sequence that is not a multiple of 32 bases, the final u64 will be backed up to the remainder,
//! and the rest of the bits will be set to zero.
//!
//! Decoding will ignore these zero bits and return the original sequence.
//!
//!
//! ## High-Level Sequence Type
//!
//! For more complex sequence manipulation, use the [`BitNuc`] type:
//!
//! ```rust
//! use bitnuc::BitNuc;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let seq: &[u8] = b"ACGTACGT";
//! let mut packed = BitNuc::new_2bit();
//! packed.fill(seq);
//!
//! let mut dbuf = Vec::new(); // Buffer for decoded sequence
//! packed.decode_into(&mut dbuf);
//!
//! // Check that the decoded sequence matches the original
//! assert_eq!(seq, &dbuf);
//!
//! Ok(())
//! }
//! ```
//!
//! ## Memory Usage
//!
//! The 2-bit encoding provides significant memory savings:
//!
//! ```text
//! Standard encoding: 1 byte per base
//! ACGT = 4 bytes = 32 bits
//!
//! 2-bit encoding: 2 bits per base
//! ACGT = 8 bits
//! ```
//!
//! This means you can store 4 times as many sequences in the same amount of memory.
//!
//! ## Error Handling
//!
//! All operations that could fail return a [`Result`] with [`Error`]:
//!
//! ```rust
//! use bitnuc::{as_2bit, Error};
//!
//! // Invalid nucleotide
//! let err = as_2bit(b"ACGN").unwrap_err();
//! assert!(matches!(err, Error::InvalidBase(b'N')));
//!
//! // Sequence too long
//! let long_seq = vec![b'A'; 33];
//! let err = as_2bit(&long_seq).unwrap_err();
//! assert!(matches!(err, Error::SequenceTooLong(33)));
//! ```
//!
//! ## Performance Considerations
//!
//! When working with many short sequences (like k-mers), using `as_2bit` and `from_2bit`
//! directly can be more efficient than creating [`BitNuc`] instances:
//!
//! ```rust
//! use bitnuc::{as_2bit, from_2bit};
//! use std::collections::HashMap;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Efficient k-mer counting
//! let mut kmer_counts = HashMap::new();
//!
//! // Pack k-mers directly into u64s
//! let sequence = b"ACGTACGT";
//! for window in sequence.windows(4) {
//! let packed = as_2bit(window)?;
//! *kmer_counts.entry(packed).or_insert(0) += 1;
//! }
//!
//! // Count of "ACGT"
//! let acgt_packed = as_2bit(b"ACGT")?;
//! assert_eq!(kmer_counts.get(&acgt_packed), Some(&2));
//! Ok(())
//! }
//! ```
//!
//! If you are unpacking many sequences, consider reusing a buffer to avoid reallocations:
//!
//! ```rust
//! use bitnuc::{as_2bit, from_2bit};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!
//! // Pack a sequence
//! let packed = as_2bit(b"ACGT")?;
//!
//! // Reusable buffer for unpacking
//! let mut unpacked = Vec::new();
//! from_2bit(packed, 4, &mut unpacked)?;
//! assert_eq!(&unpacked, b"ACGT");
//! unpacked.clear();
//!
//! // Pack another sequence
//! let packed = as_2bit(b"TGCA")?;
//! from_2bit(packed, 4, &mut unpacked)?;
//! assert_eq!(&unpacked, b"TGCA");
//! Ok(())
//! }
//! ```
//!
//!
//! See the documentation for [`as_2bit`] and [`from_2bit`] for more details on
//! working with packed sequences directly.
pub use Error;
pub use ;
pub use ;
pub use ;