Skip to main content

ebi_objects/traits/
infoable.rs

1use anyhow::Result;
2use ebi_activity_key::ActivityKey;
3use ebi_arithmetic::{
4    Fraction, MaybeExact,
5    malachite::{base::num::logic::traits::SignificantBits, rational::Rational},
6};
7
8pub trait Infoable {
9    fn info(&self, f: &mut impl std::io::Write) -> Result<()>;
10}
11
12impl Infoable for String {
13    fn info(&self, f: &mut impl std::io::Write) -> Result<()> {
14        Ok(writeln!(f, "Length\t{}", self.len())?)
15    }
16}
17
18impl Infoable for Rational {
19    fn info(&self, f: &mut impl std::io::Write) -> Result<()> {
20        Ok(write!(f, "{} bits", self.significant_bits(),)?)
21    }
22}
23
24impl Infoable for Fraction {
25    fn info(&self, f: &mut impl std::io::Write) -> Result<()> {
26        match (self.approx_ref(), self.exact_ref()) {
27            (Ok(_), Ok(fr)) => fr.info(f),
28            (Ok(fr), Err(_)) => Ok(writeln!(f, "Approximate value\t{}", fr)?),
29            (Err(_), Ok(fr)) => {
30                fr.info(f)?;
31                Ok(writeln!(f, "")?)
32            }
33            (Err(_), Err(_)) => Ok(writeln!(
34                f,
35                "Fraction is a result of combining exact and approximate arithmethic and therefore has no value."
36            )?),
37        }
38    }
39}
40
41impl Infoable for ActivityKey {
42    fn info(&self, f: &mut impl std::io::Write) -> anyhow::Result<()> {
43        let count = 20;
44
45        writeln!(f, "Activities:")?;
46        let mut labels = self.activity2name.clone();
47        labels.sort();
48        for label in labels.iter().take(count) {
49            writeln!(f, "\t{}", label)?;
50        }
51
52        if self.activity2name.len() > 20 {
53            writeln!(f, ".. ({} more)", self.activity2name.len() - count)?;
54        }
55
56        Ok(write!(f, "")?)
57    }
58}