use std::str::Utf8Error;
use llvm_support::bitcodes::{IrBlockId, StrtabCode};
use llvm_support::StrtabRef;
use thiserror::Error;
use crate::block::IrBlock;
use crate::map::{MapError, PartialMapCtx};
use crate::record::RecordBlobError;
use crate::unroll::{UnrolledBlock, UnrolledRecord};
#[derive(Debug, Error)]
pub enum StrtabError {
#[error("malformed string table: missing blob")]
MissingBlob,
#[error("invalid string table: {0}")]
BadBlob(#[from] RecordBlobError),
#[error("requested range in string table is invalid")]
BadRange,
#[error("could not decode range into a UTF-8 string: {0}")]
BadString(#[from] Utf8Error),
#[error("mapping error in string table")]
Map(#[from] MapError),
}
#[derive(Clone, Debug, Default)]
pub struct Strtab(Vec<u8>);
impl AsRef<[u8]> for Strtab {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl IrBlock for Strtab {
type Error = StrtabError;
const BLOCK_ID: IrBlockId = IrBlockId::Strtab;
fn try_map_inner(block: &UnrolledBlock, _ctx: &mut PartialMapCtx) -> Result<Self, Self::Error> {
let strtab = block
.records()
.one(StrtabCode::Blob as u64)
.ok_or(StrtabError::MissingBlob)
.and_then(|r| r.try_blob(0).map_err(StrtabError::from))?;
Ok(Self(strtab))
}
}
impl Strtab {
pub fn get(&self, sref: &StrtabRef) -> Option<&str> {
self.try_get(sref).ok()
}
pub fn try_get(&self, sref: &StrtabRef) -> Result<&str, StrtabError> {
let inner = self.as_ref();
if sref.size == 0 || sref.offset >= inner.len() || sref.offset + sref.size > inner.len() {
return Err(StrtabError::BadRange);
}
Ok(std::str::from_utf8(
&inner[sref.offset..sref.offset + sref.size],
)?)
}
pub(crate) fn read_name(&self, record: &UnrolledRecord) -> Result<&str, StrtabError> {
let fields = record.fields();
self.try_get(&(fields[0], fields[1]).into())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sref(tup: (usize, usize)) -> StrtabRef {
tup.into()
}
#[test]
fn test_strtab() {
let inner = "this is a string table";
let strtab = Strtab(inner.into());
assert_eq!(strtab.get(&sref((0, 4))).unwrap(), "this");
assert_eq!(strtab.get(&sref((0, 7))).unwrap(), "this is");
assert_eq!(strtab.get(&sref((8, 14))).unwrap(), "a string table");
assert_eq!(
strtab.get(&sref((0, inner.len()))).unwrap(),
"this is a string table"
);
assert!(strtab.get(&sref((inner.len(), 0))).is_none());
assert!(strtab.get(&sref((0, inner.len() + 1))).is_none());
assert!(strtab.get(&sref((0, 0))).is_none());
}
}