1use std::{convert::TryFrom, error::Error, sync::mpsc::Sender};
2
3use log::{debug};
4
5use crate::{binary::{Bit, BitVec}, cli::progress::ProgressStatus, context::{Context, ContextError}};
6
7pub trait Decoder<D> where D: Context {
11 fn partial_decode(&self, context: &D) -> Result<Vec<Bit>, ContextError>;
24
25 fn decode(&self, context: &mut D, progress_channel: Option<&Sender<ProgressStatus>>) -> Result<Vec<u8>, Box<dyn Error>> {
26 let mut secret = Vec::default();
27 debug!("Decoding secret from the text");
28 while context.load_text().is_ok() {
29 let mut data = self.partial_decode(&context)?;
30 if let Some(tx) = progress_channel {
31 tx.send(ProgressStatus::Step(context.get_current_text()?.len() as u64)).ok();
32 }
33 secret.append(&mut data);
34 }
35 debug!("Padding bits to byte size boundary");
36 while &secret.len() % 8 != 0 {
37 secret.push(Bit(0));
38 }
39
40 debug!("Converting bits to bytes");
41 let bit_vec: BitVec = secret.into();
42 let bytes: Vec<u8> = TryFrom::try_from(bit_vec)?;
43 Ok(bytes)
44 }
45}