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
// 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::ptr;
use std::slice;
use std::ffi;
use std::i32;
use std::f32;
use std::fmt;
use std::rc::Rc;

use ieee754::Ieee754;
use itertools::Itertools;

use bcf::header::{HeaderView, Id};
use 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(0x7F800001);
    static ref VECTOR_END_FLOAT: f32 = Ieee754::from_bits(0x7F800002);
}

/// 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 BCF record.
/// New records can be created by the `empty_record` methods of `bcf::Reader` and `bcf::Writer`.
#[derive(Debug)]
pub struct Record {
    pub inner: *mut htslib::bcf1_t,
    header: Rc<HeaderView>,
    buffer: *mut ::std::os::raw::c_void,
}

impl Record {
    pub(crate) fn new(header: Rc<HeaderView>) -> Self {
        let inner = unsafe { htslib::bcf_init() };
        Record {
            inner: inner,
            header: header,
            buffer: ptr::null_mut(),
        }
    }

    /// 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;
    }

    pub fn inner(&self) -> &htslib::bcf1_t {
        unsafe { &*self.inner }
    }

    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 `bcf::header::HeaderView::rid2name`.
    pub fn rid(&self) -> Option<u32> {
        match self.inner().rid {
            -1 => None,
            rid => Some(rid as u32),
        }
    }

    // 0-based position.
    pub fn pos(&self) -> u32 {
        self.inner().pos as u32
    }

    /// Set 0-based position.
    pub fn set_pos(&mut self, pos: i32) {
        self.inner_mut().pos = pos;
    }

    /// Update the ID string to the given value.
    pub fn set_id(&mut self, id: &[u8]) -> Result<(), IdWriteError> {
        if unsafe {
            htslib::bcf_update_id(
                self.header().inner,
                self.inner,
                ffi::CString::new(id).unwrap().as_ptr() as *mut i8,
            )
        } == 0
        {
            Ok(())
        } else {
            Err(IdWriteError::Some)
        }
    }

    /// Add the ID string (the ID field is semicolon-separated), checking for duplicates.
    pub fn push_id(&mut self, id: &[u8]) -> Result<(), IdWriteError> {
        if unsafe {
            htslib::bcf_add_id(
                self.header().inner,
                self.inner,
                ffi::CString::new(id).unwrap().as_ptr() as *mut i8,
            )
        } == 0
        {
            Ok(())
        } else {
            Err(IdWriteError::Some)
        }
    }

    /// Set the given filters IDs to the FILTER column.
    ///
    /// Setting an empty slice removes all filters.
    ///
    /// # Args
    /// - `val` - The corresponding filter string value.
    pub fn set_filters(&mut self, flt_ids: &[Id]) {
        let mut flt_ids: Vec<i32> = flt_ids.iter().map(|x| **x as i32).collect();
        unsafe {
            htslib::bcf_update_filter(
                self.header().inner,
                self.inner,
                flt_ids.as_mut_ptr(),
                flt_ids.len() as i32,
            );
        }
    }

    /// Add the given filter to the FILTER column.
    ///
    /// If `val` corresponds to `"PASS"` then all existing filters are removed first. If other than
    /// `"PASS"`, then existing `"PASS"` is removed.
    ///
    /// # Args
    /// - `val` - The corresponding filter ID value.
    pub fn push_filter(&mut self, flt_id: Id) {
        unsafe {
            htslib::bcf_add_filter(self.header().inner, self.inner, *flt_id as i32);
        }
    }

    /// Remove the given filter from the FILTER column.
    ///
    /// # Args
    /// - `val` - The corresponding filter ID.
    /// - `pass_on_empty` - Set to "PASS" when removing the last value.
    pub fn remove_filter(&mut self, flt_id: Id, pass_on_empty: bool) {
        unsafe {
            htslib::bcf_remove_filter(
                self.header().inner,
                self.inner,
                *flt_id as i32,
                pass_on_empty as i32,
            );
        }
    }

    /// Get alleles. The first allele is the reference allele.
    pub fn alleles(&self) -> Vec<&[u8]> {
        unsafe { htslib::bcf_unpack(self.inner, htslib::BCF_UN_STR 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.
    pub fn set_alleles(&mut self, alleles: &[Vec<u8>]) -> Result<(), AlleleWriteError> {
        let cstrings: Vec<ffi::CString> = alleles
            .iter()
            .map(|vec| ffi::CString::new(vec.as_slice()).unwrap())
            .collect();
        let mut ptrs: Vec<*const i8> = cstrings
            .iter()
            .map(|cstr| cstr.as_ptr() as *const i8)
            .collect();
        if unsafe {
            htslib::bcf_update_alleles(
                self.header().inner,
                self.inner,
                ptrs.as_mut_ptr(),
                alleles.len() as i32,
            )
        } == 0
        {
            Ok(())
        } else {
            Err(AlleleWriteError::Some)
        }
    }

    /// 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;
    }

    /// Get the value of the given info tag.
    pub fn info<'a>(&'a mut self, tag: &'a [u8]) -> Info {
        Info {
            record: self,
            tag: tag,
        }
    }

    /// Get the number of samples.
    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()
    }

    /// Get genotypes as vector of one `Genotype` per sample.
    pub fn genotypes(&mut self) -> Result<Genotypes, FormatReadError> {
        Ok(Genotypes {
            encoded: try!(self.format(b"GT").integer()),
        })
    }

    /// Get the value of the given format tag for each sample.
    pub fn format<'a>(&'a mut self, tag: &'a [u8]) -> Format {
        Format::new(self, tag)
    }

    /// Add an integer format tag. Data is a flattened two-dimensional array.
    /// The first dimension contains one array for each sample.
    /// Returns error if tag is not present in header.
    pub fn push_format_integer(&mut self, tag: &[u8], data: &[i32]) -> Result<(), TagWriteError> {
        self.push_format(tag, data, htslib::BCF_HT_INT)
    }

    /// Add a float format tag. Data is a flattened two-dimensional array.
    /// The first dimension contains one array for each sample.
    /// Returns error if tag is not present in header.
    pub fn push_format_float(&mut self, tag: &[u8], data: &[f32]) -> Result<(), TagWriteError> {
        self.push_format(tag, data, htslib::BCF_HT_REAL)
    }

    /// 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<(), TagWriteError> {
        assert!(data.len() > 0);
        unsafe {
            if htslib::bcf_update_format(
                self.header().inner,
                self.inner,
                ffi::CString::new(tag).unwrap().as_ptr() as *mut i8,
                data.as_ptr() as *const ::std::os::raw::c_void,
                data.len() as i32,
                ht as i32,
            ) == 0
            {
                Ok(())
            } else {
                Err(TagWriteError::Some)
            }
        }
    }

    /// Add an integer info tag.
    pub fn push_info_integer(&mut self, tag: &[u8], data: &[i32]) -> Result<(), TagWriteError> {
        self.push_info(tag, data, htslib::BCF_HT_INT)
    }

    /// Add a float info tag.
    pub fn push_info_float(&mut self, tag: &[u8], data: &[f32]) -> Result<(), TagWriteError> {
        self.push_info(tag, data, htslib::BCF_HT_REAL)
    }

    /// Add an info tag.
    pub fn push_info<T>(&mut self, tag: &[u8], data: &[T], ht: u32) -> Result<(), TagWriteError> {
        assert!(data.len() > 0);
        unsafe {
            if htslib::bcf_update_info(
                self.header().inner,
                self.inner,
                ffi::CString::new(tag).unwrap().as_ptr() as *mut i8,
                data.as_ptr() as *const ::std::os::raw::c_void,
                data.len() as i32,
                ht as i32,
            ) == 0
            {
                Ok(())
            } else {
                Err(TagWriteError::Some)
            }
        }
    }

    /// Remove unused alleles.
    pub fn trim_alleles(&mut self) -> Result<(), TrimAllelesError> {
        match unsafe { htslib::bcf_trim_alleles(self.header().inner, self.inner) } {
            -1 => Err(TrimAllelesError::Some),
            _ => Ok(()),
        }
    }
}

/// Phased or unphased alleles, represented as indices.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GenotypeAllele {
    Unphased(i32),
    Phased(i32),
    UnphasedMissing,
    PhasedMissing,
}

impl GenotypeAllele {
    /// Decode given integer according to BCF standard.
    pub fn from_encoded(encoded: i32) -> Self {
        match (encoded, encoded & 1) {
            (0, 0) => GenotypeAllele::UnphasedMissing,
            (1, 1) => GenotypeAllele::PhasedMissing,
            (e, 1) => GenotypeAllele::Phased((e >> 1) - 1),
            (e, 0) => GenotypeAllele::Unphased((e >> 1) - 1),
            _ => panic!("unexpected phasing type"),
        }
    }

    /// Get the index into the list of alleles.
    pub fn index(&self) -> Option<u32> {
        match self {
            &GenotypeAllele::Unphased(i) => Some(i as u32),
            &GenotypeAllele::Phased(i) => Some(i as u32),
            &GenotypeAllele::UnphasedMissing => None,
            &GenotypeAllele::PhasedMissing => None,
        }
    }
}

impl fmt::Display for GenotypeAllele {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.index() {
            Some(a) => write!(f, "{}", a),
            None => write!(f, "."),
        }
    }
}

custom_derive! {
    /// Genotype representation as a vector of `GenotypeAllele`.
    #[derive(NewtypeDeref, Debug, Clone, PartialEq, Eq, Hash)]
    pub struct Genotype(Vec<GenotypeAllele>);
}

impl fmt::Display for Genotype {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let &Genotype(ref alleles) = self;
        try!(write!(f, "{}", alleles[0]));
        for a in &alleles[1..] {
            let sep = match a {
                &GenotypeAllele::Phased(_) => '|',
                &GenotypeAllele::Unphased(_) => '/',
                &GenotypeAllele::UnphasedMissing => '/',
                &GenotypeAllele::PhasedMissing => '|',
            };
            try!(write!(f, "{}{}", sep, a));
        }
        Ok(())
    }
}

/// Lazy representation of genotypes, that does no computation until a particular genotype is queried.
#[derive(Debug, Clone)]
pub struct Genotypes<'a> {
    encoded: Vec<&'a [i32]>,
}

impl<'a> Genotypes<'a> {
    /// Get genotype of ith sample. So far, only supports diploid genotypes.
    ///
    /// Note that the result complies with the BCF spec. This means that the
    /// first allele will always be marked as `Unphased`. That is, if you have 1|1 in the VCF,
    /// this method will return `[Unphased(1), Phased(1)]`.
    pub fn get(&self, i: usize) -> Genotype {
        let igt = self.encoded[i];
        let gt = Genotype(
            igt.into_iter()
                .map(|&e| GenotypeAllele::from_encoded(e))
                .collect_vec(),
        );
        gt
    }
}

impl Drop for Record {
    fn drop(&mut self) {
        if !self.buffer.is_null() {
            unsafe { ::libc::free(self.buffer as *mut ::libc::c_void) };
        }
        unsafe { htslib::bcf_destroy(self.inner) };
    }
}

unsafe impl Send for Record {}
unsafe impl Sync for Record {}

/// Info tag representation.
#[derive(Debug)]
pub struct Info<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
}

impl<'a> Info<'a> {
    fn data(&mut self, data_type: u32) -> Result<Option<(usize, i32)>, InfoReadError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::bcf_get_info_values(
                self.record.header().inner,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type as i32,
            )
        } {
            -1 => Err(InfoReadError::UndefinedTag),
            -2 => Err(InfoReadError::UnexpectedType),
            -3 => Ok(None),
            ret => Ok(Some((n as usize, ret))),
        }
    }

    /// Get integers from tag. `None` if tag not present in record.
    /// Import `bcf::record::Numeric` for missing value handling.
    pub fn integer(&mut self) -> Result<Option<&'a [i32]>, InfoReadError> {
        self.data(htslib::BCF_HT_INT).map(|data| {
            data.map(|(n, _)| {
                trim_slice(unsafe { slice::from_raw_parts(self.record.buffer as *const i32, n) })
            })
        })
    }

    /// Get mutable integers from tag. `None` if tag not present in record.
    /// Import `bcf::record::Numeric` for missing value handling.
    pub fn integer_mut(&mut self) -> Result<Option<&'a mut [i32]>, InfoReadError> {
        self.data(htslib::BCF_HT_INT).map(|data| {
            data.map(|(n, _)| unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut i32, n)
            })
        })
    }

    /// Get floats from tag. `None` if tag not present in record.
    /// Import `bcf::record::Numeric` for missing value handling.
    pub fn float(&mut self) -> Result<Option<&'a [f32]>, InfoReadError> {
        self.data(htslib::BCF_HT_REAL).map(|data| {
            data.map(|(n, _)| {
                trim_slice(unsafe { slice::from_raw_parts(self.record.buffer as *const f32, n) })
            })
        })
    }

    /// Get mutable floats from tag. `None` if tag not present in record.
    /// Import `bcf::record::Numeric` for missing value handling.
    pub fn float_mut(&mut self) -> Result<Option<&'a mut [f32]>, InfoReadError> {
        self.data(htslib::BCF_HT_REAL).map(|data| {
            data.map(|(n, _)| unsafe {
                slice::from_raw_parts_mut(self.record.buffer as *mut f32, n)
            })
        })
    }

    pub fn flag(&mut self) -> Result<bool, InfoReadError> {
        self.data(htslib::BCF_HT_FLAG).map(|data| match data {
            Some((_, ret)) => ret == 1,
            None => false,
        })
    }

    /// Get strings from tag. `None` if tag not present in record.
    pub fn string(&mut self) -> Result<Option<Vec<&'a [u8]>>, InfoReadError> {
        self.data(htslib::BCF_HT_STR).map(|data| {
            data.map(|(n, ret)| {
                unsafe { slice::from_raw_parts(self.record.buffer as *const u8, ret as usize) }
                    .chunks(n)
                    .map(|s| {
                        // stop at zero character
                        s.split(|c| *c == 0u8)
                            .next()
                            .expect("Bug: returned string should not be empty.")
                    })
                    .collect()
            })
        })
    }

    /// Get mutable strings from tag. `None` if tag not present in record.
    pub fn string_mut(&mut self) -> Result<Option<Vec<&'a mut [u8]>>, InfoReadError> {
        self.data(htslib::BCF_HT_STR).map(|data| {
            data.map(|(n, ret)| {
                unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut u8, ret as usize) }
                    .chunks_mut(n)
                    .collect()
            })
        })
    }
}

unsafe impl<'a> Send for Info<'a> {}
unsafe impl<'a> Sync for Info<'a> {}

fn trim_slice<T: PartialEq + NumericUtils>(s: &[T]) -> &[T] {
    s.split(|v| v.is_vector_end())
        .next()
        .expect("Bug: returned slice should not be empty.")
}

// Representation of per-sample data.
#[derive(Debug)]
pub struct Format<'a> {
    record: &'a mut Record,
    tag: &'a [u8],
    inner: *mut htslib::bcf_fmt_t,
}

impl<'a> Format<'a> {
    /// Create new format data in a given record.
    fn new(record: &'a mut Record, tag: &'a [u8]) -> Format<'a> {
        let inner = unsafe {
            htslib::bcf_get_fmt(
                record.header().inner,
                record.inner,
                ffi::CString::new(tag).unwrap().as_ptr() as *mut i8,
            )
        };
        Format {
            record: record,
            tag: tag,
            inner: inner,
        }
    }

    pub fn inner(&self) -> &htslib::bcf_fmt_t {
        unsafe { &*self.inner }
    }

    pub fn inner_mut(&mut self) -> &mut htslib::bcf_fmt_t {
        unsafe { &mut *self.inner }
    }

    fn values_per_sample(&self) -> usize {
        self.inner().n as usize
    }

    /// Read and decode format data into a given type.
    fn data(&mut self, data_type: u32) -> Result<(usize, i32), FormatReadError> {
        let mut n: i32 = 0;
        match unsafe {
            htslib::bcf_get_format_values(
                self.record.header().inner,
                self.record.inner,
                ffi::CString::new(self.tag).unwrap().as_ptr() as *mut i8,
                &mut self.record.buffer,
                &mut n,
                data_type as i32,
            )
        } {
            -1 => Err(FormatReadError::UndefinedTag),
            -2 => Err(FormatReadError::UnexpectedType),
            -3 => Err(FormatReadError::MissingTag),
            ret => Ok((n as usize, ret)),
        }
    }

    /// Get format data as integers.
    pub fn integer(&mut self) -> Result<Vec<&'a [i32]>, FormatReadError> {
        self.data(htslib::BCF_HT_INT).map(|(n, _)| {
            unsafe { slice::from_raw_parts(self.record.buffer as *const i32, n) }
                .chunks(self.values_per_sample())
                .map(|s| trim_slice(s))
                .collect()
        })
    }

    /// Get format data as mutable integers.
    pub fn integer_mut(&mut self) -> Result<Vec<&'a mut [i32]>, FormatReadError> {
        self.data(htslib::BCF_HT_INT).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut i32, n) }
                .chunks_mut(self.values_per_sample())
                .collect()
        })
    }

    /// Get format data as floats.
    pub fn float(&mut self) -> Result<Vec<&'a [f32]>, FormatReadError> {
        self.data(htslib::BCF_HT_REAL).map(|(n, _)| {
            unsafe { slice::from_raw_parts(self.record.buffer as *const f32, n) }
                .chunks(self.values_per_sample())
                .map(|s| trim_slice(s))
                .collect()
        })
    }

    /// Get format data as mutable floats.
    pub fn float_mut(&mut self) -> Result<Vec<&'a mut [f32]>, FormatReadError> {
        self.data(htslib::BCF_HT_REAL).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut f32, n) }
                .chunks_mut(self.values_per_sample())
                .collect()
        })
    }

    /// Get format data as byte slices. To obtain the values strings, use `std::str::from_utf8`.
    pub fn string(&mut self) -> Result<Vec<&'a [u8]>, FormatReadError> {
        self.data(htslib::BCF_HT_STR).map(|(n, _)| {
            unsafe { slice::from_raw_parts(self.record.buffer as *const u8, n) }
                .chunks(self.values_per_sample())
                .map(|s| {
                    // stop at zero character
                    s.split(|c| *c == 0u8)
                        .next()
                        .expect("Bug: returned string should not be empty.")
                })
                .collect()
        })
    }

    /// Get format data as mutable byte slices.
    pub fn string_mut(&mut self) -> Result<Vec<&'a mut [u8]>, FormatReadError> {
        self.data(htslib::BCF_HT_STR).map(|(n, _)| {
            unsafe { slice::from_raw_parts_mut(self.record.buffer as *mut u8, n) }
                .chunks_mut(self.values_per_sample())
                .collect()
        })
    }
}

unsafe impl<'a> Send for Format<'a> {}
unsafe impl<'a> Sync for Format<'a> {}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum InfoReadError {
        UndefinedTag {
            description("tag undefined in header")
        }
        UnexpectedType {
            description("tag type differs from header definition")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum FormatReadError {
        UndefinedTag {
            description("tag undefined in header")
        }
        UnexpectedType {
            description("tag type differs from header definition")
        }
        MissingTag {
            description("tag missing from record")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum TagWriteError {
        Some {
            description("error writing tag to record")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum IdWriteError {
        Some {
            description("error writing ID to record")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum AlleleWriteError {
        Some {
            description("error writing alleles to record")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum FilterWriteError {
        Some {
            description("error writing filters to record")
        }
    }
}

quick_error! {
    #[derive(Debug, Clone)]
    pub enum TrimAllelesError {
        Some {
            description("error trimming alleles")
        }
    }
}