-
Notifications
You must be signed in to change notification settings - Fork 80
/
record.rs
1700 lines (1556 loc) · 57 KB
/
record.rs
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::borrow::{Borrow, BorrowMut};
use std::f32;
use std::ffi;
use std::fmt;
use std::i32;
use std::marker::PhantomData;
use std::ops::Deref;
use std::os::raw::c_char;
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::str;
use bio_types::genome;
use derive_new::new;
use ieee754::Ieee754;
use lazy_static::lazy_static;
use crate::bcf::header::{HeaderView, Id};
use crate::bcf::Error;
use crate::errors::Result;
use crate::htslib;
const MISSING_INTEGER: i32 = i32::MIN;
const VECTOR_END_INTEGER: i32 = i32::MIN + 1;
lazy_static! {
static ref MISSING_FLOAT: f32 = Ieee754::from_bits(0x7F80_0001);
static ref VECTOR_END_FLOAT: f32 = Ieee754::from_bits(0x7F80_0002);
}
/// Common methods for numeric INFO and FORMAT entries
pub trait Numeric {
/// Return true if entry is a missing value
fn is_missing(&self) -> bool;
/// Return missing value for storage in BCF record.
fn missing() -> Self;
}
impl Numeric for f32 {
fn is_missing(&self) -> bool {
self.bits() == MISSING_FLOAT.bits()
}
fn missing() -> f32 {
*MISSING_FLOAT
}
}
impl Numeric for i32 {
fn is_missing(&self) -> bool {
*self == MISSING_INTEGER
}
fn missing() -> i32 {
MISSING_INTEGER
}
}
trait NumericUtils {
/// Return true if entry marks the end of the record.
fn is_vector_end(&self) -> bool;
}
impl NumericUtils for f32 {
fn is_vector_end(&self) -> bool {
self.bits() == VECTOR_END_FLOAT.bits()
}
}
impl NumericUtils for i32 {
fn is_vector_end(&self) -> bool {
*self == VECTOR_END_INTEGER
}
}
/// A trait to allow for seamless use of bytes or integer identifiers for filters
pub trait FilterId {
fn id_from_header(&self, header: &HeaderView) -> Result<Id>;
fn is_pass(&self) -> bool;
}
impl FilterId for [u8] {
fn id_from_header(&self, header: &HeaderView) -> Result<Id> {
header.name_to_id(self)
}
fn is_pass(&self) -> bool {
matches!(self, b"PASS" | b".")
}
}
impl FilterId for Id {
fn id_from_header(&self, _header: &HeaderView) -> Result<Id> {
Ok(*self)
}
fn is_pass(&self) -> bool {
*self == Id(0)
}
}
/// A buffer for info or format data.
#[derive(Debug)]
pub struct Buffer {
inner: *mut ::std::os::raw::c_void,
len: i32,
}
impl Buffer {
pub fn new() -> Self {
Buffer {
inner: ptr::null_mut(),
len: 0,
}
}
}
impl Drop for Buffer {
fn drop(&mut self) {
unsafe {
::libc::free(self.inner as *mut ::libc::c_void);
}
}
}
#[derive(new, Debug)]
pub struct BufferBacked<'a, T: 'a + fmt::Debug, B: Borrow<Buffer> + 'a> {
value: T,
buffer: B,
#[new(default)]
phantom: PhantomData<&'a B>,
}
impl<'a, T: 'a + fmt::Debug, B: Borrow<Buffer> + 'a> Deref for BufferBacked<'a, T, B> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<'a, T: 'a + fmt::Debug + fmt::Display, B: Borrow<Buffer> + 'a> fmt::Display
for BufferBacked<'a, T, B>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.value, f)
}
}
/// A VCF/BCF record.
/// New records can be created by the `empty_record` methods of [`bcf::Reader`](crate::bcf::Reader)
/// and [`bcf::Writer`](crate::bcf::Writer).
/// # Example
/// ```rust
/// use rust_htslib::bcf::{Format, Writer};
/// use rust_htslib::bcf::header::Header;
///
/// // Create minimal VCF header with a single sample
/// let mut header = Header::new();
/// header.push_sample("sample".as_bytes());
///
/// // Write uncompressed VCF to stdout with above header and get an empty record
/// let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// let mut record = vcf.empty_record();
/// ```
#[derive(Debug)]
pub struct Record {
pub inner: *mut htslib::bcf1_t,
header: Rc<HeaderView>,
}
impl Record {
/// Construct record with reference to header `HeaderView`, for create-internal use.
pub(crate) fn new(header: Rc<HeaderView>) -> Self {
let inner = unsafe {
let inner = htslib::bcf_init();
// Always unpack record.
htslib::bcf_unpack(inner, htslib::BCF_UN_ALL as i32);
inner
};
Record { inner, header }
}
/// Force unpacking of internal record values.
pub fn unpack(&mut self) {
unsafe { htslib::bcf_unpack(self.inner, htslib::BCF_UN_ALL as i32) };
}
/// Return associated header.
pub fn header(&self) -> &HeaderView {
self.header.as_ref()
}
/// Set the record header.
pub(crate) fn set_header(&mut self, header: Rc<HeaderView>) {
self.header = header;
}
/// Return reference to the inner C struct.
///
/// # Remarks
///
/// Note that this function is only required as long as Rust-Htslib does not provide full
/// access to all aspects of Htslib.
pub fn inner(&self) -> &htslib::bcf1_t {
unsafe { &*self.inner }
}
/// Return mutable reference to inner C struct.
///
/// # Remarks
///
/// Note that this function is only required as long as Rust-Htslib does not provide full
/// access to all aspects of Htslib.
pub fn inner_mut(&mut self) -> &mut htslib::bcf1_t {
unsafe { &mut *self.inner }
}
/// Get the reference id of the record.
///
/// To look up the contig name,
/// use [`HeaderView::rid2name`](../header/struct.HeaderView.html#method.rid2name).
///
/// # Returns
///
/// - `Some(rid)` if the internal `rid` is set to a value that is not `-1`
/// - `None` if the internal `rid` is set to `-1`
pub fn rid(&self) -> Option<u32> {
match self.inner().rid {
-1 => None,
rid => Some(rid as u32),
}
}
/// Update the reference id of the record.
///
/// To look up reference id for a contig name,
/// use [`HeaderView::name2rid`](../header/struct.HeaderView.html#method.name2rid).
///
/// # Example
///
/// Example assumes we have a Record `record` from a VCF with a header containing region
/// named `1`. See [module documentation](../index.html#example-writing) for how to set
/// up VCF, header, and record.
///
/// ```
/// # use rust_htslib::bcf::{Format, Writer};
/// # use rust_htslib::bcf::header::Header;
/// # let mut header = Header::new();
/// # let header_contig_line = r#"##contig=<ID=1,length=10>"#;
/// # header.push_record(header_contig_line.as_bytes());
/// # header.push_sample("test_sample".as_bytes());
/// # let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let rid = record.header().name2rid(b"1").ok();
/// record.set_rid(rid);
/// assert_eq!(record.rid(), rid);
/// let name = record.header().rid2name(record.rid().unwrap()).ok();
/// assert_eq!(Some("1".as_bytes()), name);
/// ```
pub fn set_rid(&mut self, rid: Option<u32>) {
match rid {
Some(rid) => self.inner_mut().rid = rid as i32,
None => self.inner_mut().rid = -1,
}
}
/// Return **0-based** position
pub fn pos(&self) -> i64 {
self.inner().pos
}
/// Set **0-based** position
pub fn set_pos(&mut self, pos: i64) {
self.inner_mut().pos = pos;
}
/// Return the **0-based, exclusive** end position
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Header, Writer};
/// # use tempfile::NamedTempFile;
/// # let tmp = NamedTempFile::new().unwrap();
/// # let path = tmp.path();
/// # let header = Header::new();
/// # let vcf = Writer::from_path(path, &header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let alleles: &[&[u8]] = &[b"AGG", b"TG"];
/// record.set_alleles(alleles).expect("Failed to set alleles");
/// record.set_pos(5);
///
/// assert_eq!(record.end(), 8)
/// ```
pub fn end(&self) -> i64 {
self.pos() + self.rlen()
}
/// Return the value of the ID column.
///
/// When empty, returns `b".".to_vec()`.
pub fn id(&self) -> Vec<u8> {
if self.inner().d.id.is_null() {
b".".to_vec()
} else {
let id = unsafe { ffi::CStr::from_ptr(self.inner().d.id) };
id.to_bytes().to_vec()
}
}
/// Update the ID string to the given value.
pub fn set_id(&mut self, id: &[u8]) -> Result<()> {
let c_str = ffi::CString::new(id).unwrap();
if unsafe {
htslib::bcf_update_id(
self.header().inner,
self.inner,
c_str.as_ptr() as *mut c_char,
)
} == 0
{
Ok(())
} else {
Err(Error::BcfSetValues)
}
}
/// Clear the ID column (set it to `"."`).
pub fn clear_id(&mut self) -> Result<()> {
let c_str = ffi::CString::new(&b"."[..]).unwrap();
if unsafe {
htslib::bcf_update_id(
self.header().inner,
self.inner,
c_str.as_ptr() as *mut c_char,
)
} == 0
{
Ok(())
} else {
Err(Error::BcfSetValues)
}
}
/// Add the ID string (the ID field is semicolon-separated), checking for duplicates.
pub fn push_id(&mut self, id: &[u8]) -> Result<()> {
let c_str = ffi::CString::new(id).unwrap();
if unsafe {
htslib::bcf_add_id(
self.header().inner,
self.inner,
c_str.as_ptr() as *mut c_char,
)
} == 0
{
Ok(())
} else {
Err(Error::BcfSetValues)
}
}
/// Return `Filters` iterator for enumerating all filters that have been set.
///
/// A record having the `PASS` filter will return an empty `Filter` here.
pub fn filters(&self) -> Filters<'_> {
Filters::new(self)
}
/// Query whether the filter with the given ID has been set.
///
/// This method can be used to check if a record passes filtering by using either `Id(0)`,
/// `PASS` or `.`
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Header, Writer};
/// # use rust_htslib::bcf::header::Id;
/// # use tempfile::NamedTempFile;
/// # let tmp = tempfile::NamedTempFile::new().unwrap();
/// # let path = tmp.path();
/// let mut header = Header::new();
/// header.push_record(br#"##FILTER=<ID=foo,Description="sample is a foo fighter">"#);
/// # let vcf = Writer::from_path(path, &header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// assert!(record.has_filter("PASS".as_bytes()));
/// assert!(record.has_filter(".".as_bytes()));
/// assert!(record.has_filter(&Id(0)));
///
/// record.push_filter("foo".as_bytes()).unwrap();
/// assert!(record.has_filter("foo".as_bytes()));
/// assert!(!record.has_filter("PASS".as_bytes()))
/// ```
pub fn has_filter<T: FilterId + ?Sized>(&self, flt_id: &T) -> bool {
if flt_id.is_pass() && self.inner().d.n_flt == 0 {
return true;
}
let id = match flt_id.id_from_header(self.header()) {
Ok(i) => *i,
Err(_) => return false,
};
for i in 0..(self.inner().d.n_flt as isize) {
if unsafe { *self.inner().d.flt.offset(i) } == id as i32 {
return true;
}
}
false
}
/// Set the given filter IDs to the FILTER column.
///
/// Setting an empty slice removes all filters and sets `PASS`.
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Header, Writer};
/// # use rust_htslib::bcf::header::Id;
/// # use tempfile::NamedTempFile;
/// # let tmp = tempfile::NamedTempFile::new().unwrap();
/// # let path = tmp.path();
/// let mut header = Header::new();
/// header.push_record(br#"##FILTER=<ID=foo,Description="sample is a foo fighter">"#);
/// header.push_record(br#"##FILTER=<ID=bar,Description="a horse walks into...">"#);
/// # let vcf = Writer::from_path(path, &header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let foo = record.header().name_to_id(b"foo").unwrap();
/// let bar = record.header().name_to_id(b"bar").unwrap();
/// assert!(record.has_filter("PASS".as_bytes()));
/// let mut filters = vec![&foo, &bar];
/// record.set_filters(&filters).unwrap();
/// assert!(record.has_filter(&foo));
/// assert!(record.has_filter(&bar));
/// assert!(!record.has_filter("PASS".as_bytes()));
/// filters.clear();
/// record.set_filters(&filters).unwrap();
/// assert!(record.has_filter("PASS".as_bytes()));
/// assert!(!record.has_filter("foo".as_bytes()));
/// // 'baz' isn't in the header
/// assert!(record.set_filters(&["baz".as_bytes()]).is_err())
/// ```
///
/// # Errors
/// If any of the filter IDs do not exist in the header, an [`Error::BcfUnknownID`] is returned.
///
pub fn set_filters<T: FilterId + ?Sized>(&mut self, flt_ids: &[&T]) -> Result<()> {
let mut ids: Vec<i32> = flt_ids
.iter()
.map(|id| id.id_from_header(self.header()).map(|id| *id as i32))
.collect::<Result<Vec<i32>>>()?;
unsafe {
htslib::bcf_update_filter(
self.header().inner,
self.inner,
ids.as_mut_ptr(),
ids.len() as i32,
);
};
Ok(())
}
/// Add the given filter to the FILTER column.
///
/// If `flt_id` is `PASS` or `.` then all existing filters are removed first. Otherwise,
/// any existing `PASS` filter is removed.
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Header, Writer};
/// # use tempfile::NamedTempFile;
/// # let tmp = tempfile::NamedTempFile::new().unwrap();
/// # let path = tmp.path();
/// let mut header = Header::new();
/// header.push_record(br#"##FILTER=<ID=foo,Description="sample is a foo fighter">"#);
/// header.push_record(br#"##FILTER=<ID=bar,Description="dranks">"#);
/// # let vcf = Writer::from_path(path, &header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let foo = "foo".as_bytes();
/// let bar = record.header().name_to_id(b"bar").unwrap();
/// assert!(record.has_filter("PASS".as_bytes()));
///
/// record.push_filter(foo).unwrap();
/// record.push_filter(&bar).unwrap();
/// assert!(record.has_filter(foo));
/// assert!(record.has_filter(&bar));
/// // filter must exist in the header
/// assert!(record.push_filter("baz".as_bytes()).is_err())
/// ```
///
/// # Errors
/// If the `flt_id` does not exist in the header, an [`Error::BcfUnknownID`] is returned.
///
pub fn push_filter<T: FilterId + ?Sized>(&mut self, flt_id: &T) -> Result<()> {
let id = flt_id.id_from_header(self.header())?;
unsafe {
htslib::bcf_add_filter(self.header().inner, self.inner, *id as i32);
};
Ok(())
}
/// Remove the given filter from the FILTER column.
///
/// # Arguments
///
/// - `flt_id` - The corresponding filter ID to remove.
/// - `pass_on_empty` - Set to `PASS` when removing the last filter.
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Header, Writer};
/// # use tempfile::NamedTempFile;
/// # let tmp = tempfile::NamedTempFile::new().unwrap();
/// # let path = tmp.path();
/// let mut header = Header::new();
/// header.push_record(br#"##FILTER=<ID=foo,Description="sample is a foo fighter">"#);
/// header.push_record(br#"##FILTER=<ID=bar,Description="a horse walks into...">"#);
/// # let vcf = Writer::from_path(path, &header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let foo = "foo".as_bytes();
/// let bar = "bar".as_bytes();
/// record.set_filters(&[foo, bar]).unwrap();
/// assert!(record.has_filter(foo));
/// assert!(record.has_filter(bar));
///
/// record.remove_filter(foo, true).unwrap();
/// assert!(!record.has_filter(foo));
/// assert!(record.has_filter(bar));
/// // 'baz' is not in the header
/// assert!(record.remove_filter("baz".as_bytes(), true).is_err());
///
/// record.remove_filter(bar, true).unwrap();
/// assert!(!record.has_filter(bar));
/// assert!(record.has_filter("PASS".as_bytes()));
/// ```
///
/// # Errors
/// If the `flt_id` does not exist in the header, an [`Error::BcfUnknownID`] is returned.
///
pub fn remove_filter<T: FilterId + ?Sized>(
&mut self,
flt_id: &T,
pass_on_empty: bool,
) -> Result<()> {
let id = flt_id.id_from_header(self.header())?;
unsafe {
htslib::bcf_remove_filter(
self.header().inner,
self.inner,
*id as i32,
pass_on_empty as i32,
)
};
Ok(())
}
/// Get alleles strings.
///
/// The first allele is the reference allele.
pub fn alleles(&self) -> Vec<&[u8]> {
unsafe { htslib::bcf_unpack(self.inner, htslib::BCF_UN_ALL as i32) };
let n = self.inner().n_allele() as usize;
let dec = self.inner().d;
let alleles = unsafe { slice::from_raw_parts(dec.allele, n) };
(0..n)
.map(|i| unsafe { ffi::CStr::from_ptr(alleles[i]).to_bytes() })
.collect()
}
/// Set alleles. The first allele is the reference allele.
///
/// # Example
/// ```rust
/// # use rust_htslib::bcf::{Format, Writer};
/// # use rust_htslib::bcf::header::Header;
/// #
/// # // Create minimal VCF header with a single sample
/// # let mut header = Header::new();
/// # header.push_sample("sample".as_bytes());
/// #
/// # // Write uncompressed VCF to stdout with above header and get an empty record
/// # let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// assert_eq!(record.allele_count(), 0);
///
/// let alleles: &[&[u8]] = &[b"A", b"TG"];
/// record.set_alleles(alleles).expect("Failed to set alleles");
/// assert_eq!(record.allele_count(), 2)
/// ```
pub fn set_alleles(&mut self, alleles: &[&[u8]]) -> Result<()> {
let cstrings: Vec<ffi::CString> = alleles
.iter()
.map(|vec| ffi::CString::new(*vec).unwrap())
.collect();
let mut ptrs: Vec<*const c_char> = cstrings
.iter()
.map(|cstr| cstr.as_ptr() as *const c_char)
.collect();
if unsafe {
htslib::bcf_update_alleles(
self.header().inner,
self.inner,
ptrs.as_mut_ptr(),
alleles.len() as i32,
)
} == 0
{
Ok(())
} else {
Err(Error::BcfSetValues)
}
}
/// Get variant quality.
pub fn qual(&self) -> f32 {
self.inner().qual
}
/// Set variant quality.
pub fn set_qual(&mut self, qual: f32) {
self.inner_mut().qual = qual;
}
pub fn info<'a>(&'a self, tag: &'a [u8]) -> Info<'a, Buffer> {
self.info_shared_buffer(tag, Buffer::new())
}
/// Get the value of the given info tag.
pub fn info_shared_buffer<'a, 'b, B: BorrowMut<Buffer> + Borrow<Buffer> + 'b>(
&'a self,
tag: &'a [u8],
buffer: B,
) -> Info<'a, B> {
Info {
record: self,
tag,
buffer,
}
}
/// Get the number of samples in the record.
pub fn sample_count(&self) -> u32 {
self.inner().n_sample()
}
/// Get the number of alleles, including reference allele.
pub fn allele_count(&self) -> u32 {
self.inner().n_allele()
}
/// Add/replace genotypes in FORMAT GT tag.
///
/// # Arguments
///
/// - `genotypes` - a flattened, two-dimensional array of GenotypeAllele,
/// the first dimension contains one array for each sample.
///
/// # Errors
///
/// Returns error if GT tag is not present in header.
///
/// # Example
///
/// Example assumes we have a Record `record` from a VCF with a `GT` `FORMAT` tag.
/// See [module documentation](../index.html#example-writing) for how to set up
/// VCF, header, and record.
///
/// ```
/// # use rust_htslib::bcf::{Format, Writer};
/// # use rust_htslib::bcf::header::Header;
/// # use rust_htslib::bcf::record::GenotypeAllele;
/// # let mut header = Header::new();
/// # let header_contig_line = r#"##contig=<ID=1,length=10>"#;
/// # header.push_record(header_contig_line.as_bytes());
/// # let header_gt_line = r#"##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">"#;
/// # header.push_record(header_gt_line.as_bytes());
/// # header.push_sample("test_sample".as_bytes());
/// # let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// let alleles = &[GenotypeAllele::Unphased(1), GenotypeAllele::Unphased(1)];
/// record.push_genotypes(alleles);
/// assert_eq!("1/1", &format!("{}", record.genotypes().unwrap().get(0)));
/// ```
pub fn push_genotypes(&mut self, genotypes: &[GenotypeAllele]) -> Result<()> {
let encoded: Vec<i32> = genotypes.iter().map(|gt| i32::from(*gt)).collect();
self.push_format_integer(b"GT", &encoded)
}
/// Get genotypes as vector of one `Genotype` per sample.
///
/// # Example
/// Parsing genotype field (`GT` tag) from a VCF record:
/// ```
/// use crate::rust_htslib::bcf::{Reader, Read};
/// let mut vcf = Reader::from_path(&"test/test_string.vcf").expect("Error opening file.");
/// let expected = ["./1", "1|1", "0/1", "0|1", "1|.", "1/1"];
/// for (rec, exp_gt) in vcf.records().zip(expected.iter()) {
/// let mut rec = rec.expect("Error reading record.");
/// let genotypes = rec.genotypes().expect("Error reading genotypes");
/// assert_eq!(&format!("{}", genotypes.get(0)), exp_gt);
/// }
/// ```
pub fn genotypes(&self) -> Result<Genotypes<'_, Buffer>> {
self.genotypes_shared_buffer(Buffer::new())
}
/// Get genotypes as vector of one `Genotype` per sample, using a given shared buffer
/// to avoid unnecessary allocations.
pub fn genotypes_shared_buffer<'a, B>(&self, buffer: B) -> Result<Genotypes<'a, B>>
where
B: BorrowMut<Buffer> + Borrow<Buffer> + 'a,
{
Ok(Genotypes {
encoded: self.format_shared_buffer(b"GT", buffer).integer()?,
})
}
/// Retrieve data for a `FORMAT` field
///
/// # Example
/// *Note: some boilerplate for the example is hidden for clarity. See [module documentation](../index.html#example-writing)
/// for an example of the setup used here.*
///
/// ```rust
/// # use rust_htslib::bcf::{Format, Writer};
/// # use rust_htslib::bcf::header::Header;
/// #
/// # // Create minimal VCF header with a single sample
/// # let mut header = Header::new();
/// header.push_sample(b"sample1").push_sample(b"sample2").push_record(br#"##FORMAT=<ID=DP,Number=1,Type=Integer,Description="Read Depth">"#);
/// #
/// # // Write uncompressed VCF to stdout with above header and get an empty record
/// # let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// record.push_format_integer(b"DP", &[20, 12]).expect("Failed to set DP format field");
///
/// let read_depths = record.format(b"DP").integer().expect("Couldn't retrieve DP field");
/// let sample1_depth = read_depths[0];
/// assert_eq!(sample1_depth, &[20]);
/// let sample2_depth = read_depths[1];
/// assert_eq!(sample2_depth, &[12])
/// ```
///
/// # Errors
/// **Attention:** the returned [`BufferBacked`] from [`integer()`](Format::integer)
/// (`read_depths`), which holds the data, has to be kept in scope as long as the data is
/// accessed. If parts of the data are accessed after the `BufferBacked` object is been
/// dropped, you will access unallocated memory.
pub fn format<'a>(&'a self, tag: &'a [u8]) -> Format<'a, Buffer> {
self.format_shared_buffer(tag, Buffer::new())
}
/// Get the value of the given format tag for each sample.
pub fn format_shared_buffer<'a, 'b, B: BorrowMut<Buffer> + Borrow<Buffer> + 'b>(
&'a self,
tag: &'a [u8],
buffer: B,
) -> Format<'a, B> {
Format::new(self, tag, buffer)
}
/// Add/replace an integer-typed FORMAT tag.
///
/// # Arguments
///
/// - `tag` - The tag's string.
/// - `data` - a flattened, two-dimensional array, the first dimension contains one array
/// for each sample.
///
/// # Errors
///
/// Returns error if tag is not present in header.
pub fn push_format_integer(&mut self, tag: &[u8], data: &[i32]) -> Result<()> {
self.push_format(tag, data, htslib::BCF_HT_INT)
}
/// Add/replace a float-typed FORMAT tag.
///
/// # Arguments
///
/// - `tag` - The tag's string.
/// - `data` - a flattened, two-dimensional array, the first dimension contains one array
/// for each sample.
///
/// # Errors
///
/// Returns error if tag is not present in header.
///
/// # Example
///
/// Example assumes we have a Record `record` from a VCF with an `AF` `FORMAT` tag.
/// See [module documentation](../index.html#example-writing) for how to set up
/// VCF, header, and record.
///
/// ```
/// # use rust_htslib::bcf::{Format, Writer};
/// # use rust_htslib::bcf::header::Header;
/// # use rust_htslib::bcf::record::GenotypeAllele;
/// # let mut header = Header::new();
/// # let header_contig_line = r#"##contig=<ID=1,length=10>"#;
/// # header.push_record(header_contig_line.as_bytes());
/// # let header_af_line = r#"##FORMAT=<ID=AF,Number=1,Type=Float,Description="Frequency">"#;
/// # header.push_record(header_af_line.as_bytes());
/// # header.push_sample("test_sample".as_bytes());
/// # let mut vcf = Writer::from_stdout(&header, true, Format::Vcf).unwrap();
/// # let mut record = vcf.empty_record();
/// record.push_format_float(b"AF", &[0.5]);
/// assert_eq!(0.5, record.format(b"AF").float().unwrap()[0][0]);
/// ```
pub fn push_format_float(&mut self, tag: &[u8], data: &[f32]) -> Result<()> {
self.push_format(tag, data, htslib::BCF_HT_REAL)
}
/// Add/replace a single-char-typed FORMAT tag.
///
/// # Arguments
///
/// - `tag` - The tag's string.
/// - `data` - a flattened, two-dimensional array, the first dimension contains one array
/// for each sample.
///
/// # Errors
///
/// Returns error if tag is not present in header.
pub fn push_format_char(&mut self, tag: &[u8], data: &[u8]) -> Result<()> {
self.push_format(tag, data, htslib::BCF_HT_STR)
}
/// Add a format tag. Data is a flattened two-dimensional array.
/// The first dimension contains one array for each sample.
fn push_format<T>(&mut self, tag: &[u8], data: &[T], ht: u32) -> Result<()> {
let tag_c_str = ffi::CString::new(tag).unwrap();
unsafe {
if htslib::bcf_update_format(
self.header().inner,
self.inner,
tag_c_str.as_ptr() as *mut c_char,
data.as_ptr() as *const ::std::os::raw::c_void,
data.len() as i32,
ht as i32,
) == 0
{
Ok(())
} else {
Err(Error::BcfSetTag {
tag: str::from_utf8(tag).unwrap().to_owned(),
})
}
}
}
// TODO: should we add convenience methods clear_format_*?
/// Add a string-typed FORMAT tag. Note that genotypes are treated as a special case
/// and cannot be added with this method. See instead [push_genotypes](#method.push_genotypes).
///
/// # Arguments
///
/// - `tag` - The tag's string.
/// - `data` - a two-dimensional array, the first dimension contains one array
/// for each sample. Must be non-empty.
///
/// # Errors
///
/// Returns error if tag is not present in header.
pub fn push_format_string<D: Borrow<[u8]>>(&mut self, tag: &[u8], data: &[D]) -> Result<()> {
assert!(
!data.is_empty(),
"given string data must have at least 1 element"
);
let c_data = data
.iter()
.map(|s| ffi::CString::new(s.borrow()).unwrap())
.collect::<Vec<ffi::CString>>();
let c_ptrs = c_data
.iter()
.map(|s| s.as_ptr() as *mut i8)
.collect::<Vec<*mut i8>>();
let tag_c_str = ffi::CString::new(tag).unwrap();
unsafe {
if htslib::bcf_update_format_string(
self.header().inner,
self.inner,
tag_c_str.as_ptr() as *mut c_char,
c_ptrs.as_slice().as_ptr() as *mut *const c_char,
data.len() as i32,
) == 0
{
Ok(())
} else {
Err(Error::BcfSetTag {
tag: str::from_utf8(tag).unwrap().to_owned(),
})
}
}
}
/// Add/replace an integer-typed INFO entry.
pub fn push_info_integer(&mut self, tag: &[u8], data: &[i32]) -> Result<()> {
self.push_info(tag, data, htslib::BCF_HT_INT)
}
/// Remove the integer-typed INFO entry.
pub fn clear_info_integer(&mut self, tag: &[u8]) -> Result<()> {
self.push_info::<i32>(tag, &[], htslib::BCF_HT_INT)
}
/// Add/replace a float-typed INFO entry.
pub fn push_info_float(&mut self, tag: &[u8], data: &[f32]) -> Result<()> {
self.push_info(tag, data, htslib::BCF_HT_REAL)
}
/// Remove the float-typed INFO entry.
pub fn clear_info_float(&mut self, tag: &[u8]) -> Result<()> {
self.push_info::<u8>(tag, &[], htslib::BCF_HT_REAL)
}
/// Add/replace an INFO tag.
///
/// # Arguments
/// * `tag` - the tag to add/replace
/// * `data` - the data to set
/// * `ht` - the HTSLib type to use
fn push_info<T>(&mut self, tag: &[u8], data: &[T], ht: u32) -> Result<()> {
let tag_c_str = ffi::CString::new(tag).unwrap();
unsafe {
if htslib::bcf_update_info(
self.header().inner,
self.inner,
tag_c_str.as_ptr() as *mut c_char,
data.as_ptr() as *const ::std::os::raw::c_void,
data.len() as i32,
ht as i32,
) == 0
{
Ok(())
} else {
Err(Error::BcfSetTag {
tag: str::from_utf8(tag).unwrap().to_owned(),
})
}
}
}
/// Set flag into the INFO column.
pub fn push_info_flag(&mut self, tag: &[u8]) -> Result<()> {
self.push_info_string_impl(tag, &[b""], htslib::BCF_HT_FLAG)
}
/// Remove the flag from the INFO column.
pub fn clear_info_flag(&mut self, tag: &[u8]) -> Result<()> {
self.push_info_string_impl(tag, &[], htslib::BCF_HT_FLAG)
}
/// Add/replace a string-typed INFO entry.
pub fn push_info_string(&mut self, tag: &[u8], data: &[&[u8]]) -> Result<()> {
self.push_info_string_impl(tag, data, htslib::BCF_HT_STR)
}
/// Remove the string field from the INFO column.
pub fn clear_info_string(&mut self, tag: &[u8]) -> Result<()> {
self.push_info_string_impl(tag, &[], htslib::BCF_HT_STR)
}
/// Add an string-valued INFO tag.
fn push_info_string_impl(&mut self, tag: &[u8], data: &[&[u8]], ht: u32) -> Result<()> {
let mut buf: Vec<u8> = Vec::new();
for (i, &s) in data.iter().enumerate() {
if i > 0 {
buf.extend(b",");
}
buf.extend(s);
}
let c_str = ffi::CString::new(buf).unwrap();
let len = if ht == htslib::BCF_HT_FLAG {
data.len()
} else {
c_str.to_bytes().len()
};
let tag_c_str = ffi::CString::new(tag).unwrap();
unsafe {
if htslib::bcf_update_info(
self.header().inner,
self.inner,
tag_c_str.as_ptr() as *mut c_char,
c_str.as_ptr() as *const ::std::os::raw::c_void,
len as i32,
ht as i32,
) == 0
{
Ok(())
} else {
Err(Error::BcfSetTag {
tag: str::from_utf8(tag).unwrap().to_owned(),
})
}
}
}