use crate::armor::{armor, dearmor};
use crate::codec::{decode, encode};
use crate::{Error, Mode, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextForm {
Plain,
Encoded,
Armored,
}
pub fn detect(text: &str) -> TextForm {
if text.contains("BEGIN DOLDSKRIFT") {
TextForm::Armored
} else if text.chars().any(crate::is_symbol) {
TextForm::Encoded
} else {
TextForm::Plain
}
}
pub fn encode_form(text: &str, mode: Mode) -> Result<String> {
match mode {
Mode::Visual => Ok(text.to_owned()),
Mode::Encoded => encode(text),
Mode::Session => Err(Error::InvalidMapping(
"session mode needs Session::encode".into(),
)),
Mode::Protected => Err(Error::AccessDenied(
"Protected mode has no Open plaintext text-form encode".into(),
)),
}
}
pub fn decode_form(text: &str) -> Result<String> {
match detect(text) {
TextForm::Plain => Ok(text.to_owned()),
TextForm::Encoded => decode(text),
TextForm::Armored => {
let bytes = dearmor(text)?;
String::from_utf8(bytes).map_err(Error::from)
}
}
}
pub fn armor_bytes(bytes: &[u8]) -> String {
armor(bytes)
}