use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::models::Transcript;
#[derive(Serialize, Deserialize)]
pub struct Transcripts {
list: Vec<Transcript>,
name: HashMap<String, Vec<usize>>,
gene: HashMap<String, Vec<usize>>,
}
impl Transcripts {
pub fn new() -> Self {
Self {
list: vec![],
name: HashMap::new(),
gene: HashMap::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
list: Vec::with_capacity(capacity),
name: HashMap::with_capacity(capacity),
gene: HashMap::with_capacity(capacity),
}
}
pub fn by_name(&self, name: &str) -> Vec<&Transcript> {
match self.name.get(name) {
Some(ids) => {
let mut res: Vec<&Transcript> = Vec::with_capacity(ids.len());
for id in ids {
res.push(&self.list[*id]);
}
res
}
None => vec![],
}
}
pub fn by_gene(&self, gene: &str) -> Vec<&Transcript> {
match self.gene.get(gene) {
Some(ids) => {
let mut res: Vec<&Transcript> = Vec::with_capacity(ids.len());
for id in ids {
res.push(&self.list[*id]);
}
res
}
None => vec![],
}
}
pub fn push(&mut self, record: Transcript) {
let idx = self.list.len();
match self.name.get_mut(record.name()) {
Some(x) => x.push(idx),
None => {
self.name.insert(record.name().to_string(), vec![idx]);
}
}
match self.gene.get_mut(record.gene()) {
Some(x) => x.push(idx),
None => {
self.gene.insert(record.gene().to_string(), vec![idx]);
}
}
self.list.push(record);
}
pub fn len(&self) -> usize {
self.list.len()
}
pub fn is_empty(&self) -> bool {
self.list.is_empty()
}
pub fn as_vec(&self) -> &Vec<Transcript> {
&self.list
}
pub fn to_vec(self) -> Vec<Transcript> {
self.list
}
pub fn genes(&self) -> Vec<&str> {
self.gene.keys().map(|x| x.as_str()).collect()
}
}
impl Default for Transcripts {
fn default() -> Self {
Self::new()
}
}
impl IntoIterator for Transcripts {
type Item = Transcript;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.list.into_iter()
}
}