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
//! VCF header and fields.
mod builder;
pub mod file_format;
pub mod parser;
pub mod record;
pub mod string_maps;
pub use self::{
builder::Builder, file_format::FileFormat, parser::ParseError, parser::Parser, record::Record,
string_maps::StringMaps,
};
use std::{hash::Hash, str::FromStr};
use indexmap::{IndexMap, IndexSet};
use self::record::value::{
map::{AlternativeAllele, Contig, Filter, Format, Info},
Map,
};
/// VCF header info records.
pub type Infos = IndexMap<String, Map<Info>>;
/// VCF header filter records.
pub type Filters = IndexMap<String, Map<Filter>>;
/// VCF header format records.
pub type Formats = IndexMap<String, Map<Format>>;
/// VCF header alternative allele records.
pub type AlternativeAlleles = IndexMap<String, Map<AlternativeAllele>>;
/// VCF header contig records.
pub type Contigs = IndexMap<String, Map<Contig>>;
/// VCF header sample names.
pub type SampleNames = IndexSet<String>;
/// VCF header generic records.
pub type OtherRecords = IndexMap<record::key::Other, record::value::Collection>;
/// A VCF header.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Header {
file_format: FileFormat,
infos: Infos,
filters: Filters,
formats: Formats,
alternative_alleles: AlternativeAlleles,
contigs: Contigs,
sample_names: SampleNames,
other_records: OtherRecords,
string_maps: StringMaps,
}
impl Header {
/// Returns a builder to create a record from each of its fields.
///
/// # Examples
///
/// ```
/// use noodles_vcf as vcf;
/// let builder = vcf::Header::builder();
/// ```
pub fn builder() -> Builder {
Builder::default()
}
/// Returns the file format (`fileformat`) of the VCF.
///
/// `fileformat` is a required meta record and is guaranteed to be set.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::FileFormat};
///
/// let header = vcf::Header::builder()
/// .set_file_format(FileFormat::default())
/// .build();
///
/// assert_eq!(header.file_format(), FileFormat::default());
/// ```
pub fn file_format(&self) -> FileFormat {
self.file_format
}
/// Returns a mutable reference to the file format (`fileformat`) of the VCF.
///
/// `fileformat` is a required meta record and is guaranteed to be set.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::FileFormat};
///
/// let mut header = vcf::Header::default();
///
/// let file_format = FileFormat::new(4, 2);
/// *header.file_format_mut() = file_format;
///
/// assert_eq!(header.file_format(), file_format);
/// ```
pub fn file_format_mut(&mut self) -> &mut FileFormat {
&mut self.file_format
}
/// Returns a map of information records (`INFO`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::Info, Map},
/// variant::record::info::field::key,
/// };
///
/// let id = key::SAMPLES_WITH_DATA_COUNT;
/// let info = Map::<Info>::from(id);
///
/// let header = vcf::Header::builder()
/// .add_info(id, info.clone())
/// .build();
///
/// let infos = header.infos();
/// assert_eq!(infos.len(), 1);
/// assert_eq!(&infos[0], &info);
/// ```
pub fn infos(&self) -> &Infos {
&self.infos
}
/// Returns a mutable reference to a map of information records (`INFO`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::Info, Map},
/// variant::record::info::field::key,
/// };
///
/// let mut header = vcf::Header::default();
///
/// let id = key::SAMPLES_WITH_DATA_COUNT;
/// let info = Map::<Info>::from(id);
/// header.infos_mut().insert(id.into(), info.clone());
///
/// let infos = header.infos();
/// assert_eq!(infos.len(), 1);
/// assert_eq!(&infos[0], &info);
/// ```
pub fn infos_mut(&mut self) -> &mut Infos {
&mut self.infos
}
/// Returns a map of filter records (`FILTER`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::record::value::{map::Filter, Map}};
///
/// let filter = Map::<Filter>::new("Quality below 10");
///
/// let header = vcf::Header::builder()
/// .add_filter("q10", filter.clone())
/// .build();
///
/// let filters = header.filters();
/// assert_eq!(filters.len(), 1);
/// assert_eq!(&filters[0], &filter);
/// ```
pub fn filters(&self) -> &Filters {
&self.filters
}
/// Returns a mutable reference to a map of filter records (`FILTER`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::record::value::{map::Filter, Map}};
///
/// let mut header = vcf::Header::default();
///
/// let filter = Map::<Filter>::new("Quality below 10");
/// header.filters_mut().insert(String::from("q10"), filter.clone());
///
/// let filters = header.filters();
/// assert_eq!(filters.len(), 1);
/// assert_eq!(&filters[0], &filter);
/// ```
pub fn filters_mut(&mut self) -> &mut Filters {
&mut self.filters
}
/// Returns a list of genotype format records (`FORMAT`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::Format, Map},
/// variant::record::samples::keys::key,
/// };
///
/// let id = key::GENOTYPE;
/// let format = Map::<Format>::from(id);
///
/// let header = vcf::Header::builder()
/// .add_format(id, format.clone())
/// .build();
///
/// let formats = header.formats();
/// assert_eq!(formats.len(), 1);
/// assert_eq!(&formats[0], &format);
/// ```
pub fn formats(&self) -> &Formats {
&self.formats
}
/// Returns a mutable reference to a list of genotype format records (`FORMAT`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::Format, Map},
/// variant::record::samples::keys::key,
/// };
///
/// let mut header = vcf::Header::default();
///
/// let id = key::GENOTYPE;
/// let format = Map::<Format>::from(id);
/// header.formats_mut().insert(id.into(), format.clone());
///
/// let formats = header.formats();
/// assert_eq!(formats.len(), 1);
/// assert_eq!(&formats[0], &format);
/// ```
pub fn formats_mut(&mut self) -> &mut Formats {
&mut self.formats
}
/// Returns a map of symbolic alternate alleles (`ALT`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::AlternativeAllele, Map},
/// };
///
/// let alt = Map::<AlternativeAllele>::new("Deletion");
///
/// let header = vcf::Header::builder()
/// .add_alternative_allele("DEL", alt.clone())
/// .build();
///
/// let alternative_alleles = header.alternative_alleles();
/// assert_eq!(alternative_alleles.len(), 1);
/// assert_eq!(&alternative_alleles[0], &alt);
/// ```
pub fn alternative_alleles(&self) -> &AlternativeAlleles {
&self.alternative_alleles
}
/// Returns a mutable reference to a map of symbolic alternate alleles (`ALT`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::value::{map::AlternativeAllele, Map},
/// };
///
/// let mut header = vcf::Header::default();
///
/// let alt = Map::<AlternativeAllele>::new("Deletion");
/// header.alternative_alleles_mut().insert(String::from("DEL"), alt.clone());
///
/// let alternative_alleles = header.alternative_alleles();
/// assert_eq!(alternative_alleles.len(), 1);
/// assert_eq!(&alternative_alleles[0], &alt);
/// ```
pub fn alternative_alleles_mut(&mut self) -> &mut AlternativeAlleles {
&mut self.alternative_alleles
}
/// Returns a map of contig records (`contig`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::record::value::{map::Contig, Map}};
///
/// let contig = Map::<Contig>::new();
///
/// let header = vcf::Header::builder()
/// .add_contig("sq0", contig.clone())
/// .build();
///
/// let contigs = header.contigs();
/// assert_eq!(contigs.len(), 1);
/// assert_eq!(&contigs[0], &contig);
/// ```
pub fn contigs(&self) -> &Contigs {
&self.contigs
}
/// Returns a mutable reference to a map of contig records (`contig`).
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::record::value::{map::Contig, Map}};
///
/// let mut header = vcf::Header::default();
///
/// let contig = Map::<Contig>::new();
/// header.contigs_mut().insert(String::from("sq0"), contig.clone());
///
/// let contigs = header.contigs();
/// assert_eq!(contigs.len(), 1);
/// assert_eq!(&contigs[0], &contig);
/// ```
pub fn contigs_mut(&mut self) -> &mut Contigs {
&mut self.contigs
}
/// Returns a list of sample names that come after the FORMAT column in the header record.
///
/// # Examples
///
/// ```
/// use indexmap::IndexSet;
/// use noodles_vcf as vcf;
///
/// let header = vcf::Header::builder()
/// .add_sample_name("sample0")
/// .add_sample_name("sample1")
/// .build();
///
/// let expected: IndexSet<_> = [String::from("sample0"), String::from("sample1")]
/// .into_iter()
/// .collect();
///
/// assert_eq!(header.sample_names(), &expected);
/// ```
pub fn sample_names(&self) -> &SampleNames {
&self.sample_names
}
/// Returns a mutable reference to a list of sample names that come after the FORMAT column in
/// the header record.
///
/// # Examples
///
/// ```
/// use indexmap::IndexSet;
/// use noodles_vcf as vcf;
///
/// let mut header = vcf::Header::builder().add_sample_name("sample0").build();
/// header.sample_names_mut().insert(String::from("sample1"));
///
/// let expected: IndexSet<_> = [String::from("sample0"), String::from("sample1")]
/// .into_iter()
/// .collect();
///
/// assert_eq!(header.sample_names(), &expected);
/// ```
pub fn sample_names_mut(&mut self) -> &mut SampleNames {
&mut self.sample_names
}
/// Returns a map of records with nonstandard keys.
///
/// This includes all records other than `fileformat`, `INFO`, `FILTER`, `FORMAT`, `ALT`, and
/// `contig`.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{self as vcf, header::record::Value};
///
/// let header = vcf::Header::builder()
/// .insert("fileDate".parse()?, Value::from("20200709"))?
/// .build();
///
/// assert_eq!(header.other_records().len(), 1);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn other_records(&self) -> &OtherRecords {
&self.other_records
}
/// Returns a mutable reference to a map of collections of records with nonstandard keys.
///
/// This includes all records other than `fileformat`, `INFO`, `FILTER`, `FORMAT`, `ALT`, and
/// `contig`.
///
/// To simply add an nonstandard record, consider using [`Self::insert`] instead.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::{value::Collection, Value},
/// };
///
/// let mut header = vcf::Header::default();
///
/// let collection = Collection::Unstructured(vec![String::from("20200709")]);
/// header.other_records_mut().insert("fileDate".parse()?, collection.clone());
///
/// assert_eq!(header.other_records().get("fileDate"), Some(&collection));
/// # Ok::<_, vcf::header::record::key::other::ParseError>(())
/// ```
pub fn other_records_mut(&mut self) -> &mut OtherRecords {
&mut self.other_records
}
/// Returns a collection of header values with the given key.
///
/// This includes all records other than `fileformat`, `INFO`, `FILTER`, `FORMAT`, `ALT`, and
/// `contig`.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::{value::Collection, Value},
/// };
///
/// let header = vcf::Header::builder()
/// .insert("fileDate".parse()?, Value::from("20200709"))?
/// .build();
///
/// assert_eq!(
/// header.get("fileDate"),
/// Some(&Collection::Unstructured(vec![String::from("20200709")]))
/// );
///
/// assert!(header.get("reference").is_none());
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn get<Q>(&self, key: &Q) -> Option<&record::value::Collection>
where
Q: ?Sized + Hash + indexmap::Equivalent<record::key::Other>,
{
self.other_records.get(key)
}
/// Inserts a key-value pair representing a nonstandard record into the header.
///
/// # Examples
///
/// ```
/// use noodles_vcf::{
/// self as vcf,
/// header::record::{value::Collection, Value},
/// };
///
/// let mut header = vcf::Header::default();
/// assert!(header.get("fileDate").is_none());
///
/// header.insert("fileDate".parse()?, Value::from("20200709"))?;
/// assert_eq!(
/// header.get("fileDate"),
/// Some(&Collection::Unstructured(vec![String::from("20200709")]))
/// );
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub fn insert(
&mut self,
key: record::key::Other,
value: record::Value,
) -> Result<(), record::value::collection::AddError> {
let collection = self
.other_records
.entry(key)
.or_insert_with(|| match value {
record::Value::String(_) => record::value::Collection::Unstructured(Vec::new()),
record::Value::Map(..) => record::value::Collection::Structured(IndexMap::new()),
});
collection.add(value)
}
#[doc(hidden)]
pub fn string_maps(&self) -> &StringMaps {
&self.string_maps
}
#[doc(hidden)]
pub fn string_maps_mut(&mut self) -> &mut StringMaps {
&mut self.string_maps
}
}
impl Default for Header {
fn default() -> Self {
Builder::default().build()
}
}
impl FromStr for Header {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Parser::default().parse(s)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
let header = Header::default();
assert_eq!(header.file_format(), FileFormat::default());
}
#[test]
fn test_insert_with_duplicate_keys() -> Result<(), Box<dyn std::error::Error>> {
let key: record::key::Other = "noodles".parse()?;
let values = [record::Value::from("0"), record::Value::from("1")];
let mut header = Header::default();
for value in values {
header.insert(key.clone(), value)?;
}
assert_eq!(
header.get(&key),
Some(&record::value::Collection::Unstructured(vec![
String::from("0"),
String::from("1")
]))
);
Ok(())
}
}