Skip to content

Commit

Permalink
vcf/io/writer/info/field/value/string: Percent-encode special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
zaeleus committed Apr 5, 2024
1 parent 93f6791 commit b7578a5
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
2 changes: 2 additions & 0 deletions noodles-vcf/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
* vcf/io/writer/record: Add validation for IDs, reference bases, alternate
bases, and filters.

* vcf/io/writer/info/field/value/string: Percent-encode special characters.

## 0.52.0 - 2024-04-04

### Added
Expand Down
45 changes: 45 additions & 0 deletions noodles-vcf/src/io/writer/record/info/field/value/string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::io::{self, Write};

use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};

// § 1.2 "Character encoding, non-printable characters and characters with special meaning" (2023-08-23)
const PERCENT_ENCODE_SET: &AsciiSet = &CONTROLS
.add(b':')
.add(b';')
.add(b'=')
.add(b'%')
.add(b',')
.add(b'\r')
.add(b'\n')
.add(b'\t');

pub(super) fn write_string<W>(writer: &mut W, s: &str) -> io::Result<()>
where
W: Write,
{
for t in utf8_percent_encode(s, PERCENT_ENCODE_SET) {
writer.write_all(t.as_bytes())?;
}

Ok(())
}

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

#[test]
fn test_write_string() -> io::Result<()> {
let mut buf = Vec::new();

buf.clear();
write_string(&mut buf, "ndls")?;
assert_eq!(buf, b"ndls");

buf.clear();
write_string(&mut buf, "noodles=vcf;")?;
assert_eq!(buf, b"noodles%3Dvcf%3B");

Ok(())
}
}

0 comments on commit b7578a5

Please sign in to comment.