Skip to content

Commit

Permalink
Reformat as Display trait
Browse files Browse the repository at this point in the history
  • Loading branch information
ctsa committed Oct 19, 2024
1 parent 5155400 commit 7ee96e2
Showing 1 changed file with 23 additions and 26 deletions.
49 changes: 23 additions & 26 deletions src/bcf/record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,27 +1088,6 @@ impl Record {
}
"".to_owned()
}

/// Format the record as a VCF string
///
/// This method is intended for debug and error reporting purposes.
///
pub fn to_vcf_string(&self) -> String {
// int vcf_format(const bcf_hdr_t *h, const bcf1_t *v, kstring_t *s)
let mut buf = htslib::kstring_t {
l: 0,
m: 0,
s: ptr::null_mut(),
};
unsafe {
htslib::vcf_format(self.header().inner, self.inner, &mut buf);
let vcf_str = String::from(ffi::CStr::from_ptr(buf.s).to_str().unwrap());
if !buf.s.is_null() {
libc::free(buf.s as *mut libc::c_void);
}
vcf_str
}
}
}

impl Clone for Record {
Expand Down Expand Up @@ -1258,6 +1237,25 @@ unsafe impl Send for Record {}

unsafe impl Sync for Record {}

impl fmt::Display for Record {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buf = htslib::kstring_t {
l: 0,
m: 0,
s: ptr::null_mut(),
};
let vcf_str = unsafe {
htslib::vcf_format(self.header().inner, self.inner, &mut buf);
let vcf_str = String::from(ffi::CStr::from_ptr(buf.s).to_str().unwrap());
if !buf.s.is_null() {
libc::free(buf.s as *mut libc::c_void);
}
vcf_str
};
write!(f, "{vcf_str}")
}
}

/// Info tag representation.
#[derive(Debug)]
pub struct Info<'a, B: BorrowMut<Buffer> + Borrow<Buffer>> {
Expand Down Expand Up @@ -1737,17 +1735,16 @@ mod tests {
}

#[test]
fn test_record_to_vcf_string() {
fn test_record_display_trait() {
let tmp = NamedTempFile::new().unwrap();
let path = tmp.path();
let mut header = Header::new();
// Add contig records
let header_contig_line = b"##contig=<ID=chr1,length=1000>";
header.push_record(header_contig_line);
header.push_record(b"##contig=<ID=chr1,length=1000>");
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();
record.push_filter("foo".as_bytes()).unwrap();
assert_eq!(record.to_vcf_string(), "chr1\t1\t.\t.\t.\t0\tfoo\t.\n");
let s = format!("{record}");
assert_eq!(s, "chr1\t1\t.\t.\t.\t0\tfoo\t.\n");
}
}

0 comments on commit 7ee96e2

Please sign in to comment.