use anyhow::bail;
use quick_xml::events::{BytesStart, Event};
use std::io::Read;
use crate::{
common_types::Text,
excel::XmlReader,
helper::{extract_text_contents, string_to_unsignedint},
};
#[derive(Debug, Clone, PartialEq)]
pub struct XlsxPhoneticRun {
pub text: Option<Text>,
pub base_text_end_index: Option<u64>,
pub base_text_start_index: Option<u64>,
}
impl XlsxPhoneticRun {
pub(crate) fn load(reader: &mut XmlReader<impl Read>, e: &BytesStart) -> anyhow::Result<Self> {
let mut run = Self {
text: None,
base_text_end_index: None,
base_text_start_index: None,
};
let attributes = e.attributes();
for a in attributes {
match a {
Ok(a) => {
let string_value = String::from_utf8(a.value.to_vec())?;
match a.key.local_name().as_ref() {
b"eb" => {
run.base_text_end_index = string_to_unsignedint(&string_value);
}
b"sb" => {
run.base_text_start_index = string_to_unsignedint(&string_value);
}
_ => {}
}
}
Err(error) => {
bail!(error.to_string())
}
}
}
let mut buf: Vec<u8> = Vec::new();
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Start(ref e)) if e.local_name().as_ref() == b"t" => {
run.text = Some(extract_text_contents(reader, b"t")?);
}
Ok(Event::End(ref e)) if e.local_name().as_ref() == b"rPh" => break,
Ok(Event::Eof) => bail!("unexpected end of file at `rPh`."),
Err(e) => bail!(e.to_string()),
_ => (),
}
}
return Ok(run);
}
}