use std::borrow::Cow;
use crate::error::{Error, Result};
#[derive(Debug, Clone)]
pub struct ModuleImage<'a> {
data: Cow<'a, [u8]>,
}
impl<'a> ModuleImage<'a> {
pub fn from_ptx(ptx: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
let ptx = ptx.into();
let text = ptx.strip_suffix(&[0]).unwrap_or(&ptx[..]);
if text.is_empty() {
return Err(Error::empty("module image"));
}
if text.contains(&0) {
return Err(Error::InteriorNul);
}
let data = if ptx.last() == Some(&0) {
ptx
} else {
let mut terminated = ptx.into_owned();
terminated.push(0);
Cow::Owned(terminated)
};
Ok(Self { data })
}
#[cfg(any(feature = "nvrtc_13_4", feature = "nvjitlink_13_4"))]
pub(crate) fn from_compiler_output(data: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
let data = data.into();
if data.is_empty() {
return Err(Error::empty("module image"));
}
Ok(Self { data })
}
#[must_use]
pub unsafe fn from_bytes_unchecked(data: impl Into<Cow<'a, [u8]>>) -> Self {
Self { data: data.into() }
}
#[must_use]
pub fn as_ptr(&self) -> *const () {
self.data.as_ptr().cast()
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
self.data.as_ref()
}
}