use std::path::Path;
use std::ffi::OsString;
#[derive(Default)]
pub struct ContentPath {
path: String,
os: Option<OsString>,
}
impl ContentPath {
#[inline]
pub fn from_str(s: &str) -> Self {
Self { path: s.to_string(), os: None }
}
#[inline]
pub(crate) fn with_string(s: String) -> Self {
Self { path: s, os: None }
}
pub fn from_os(p: &Path) -> Self {
let os = p.as_os_str();
match os.to_str() {
Some(s) => Self { path: s.to_string(), os: None },
None => Self {
path: os.to_string_lossy().into_owned(),
os: Some(os.to_owned()),
},
}
}
#[inline]
pub fn empty() -> Self {
Self { path: String::new(), os: None }
}
#[inline]
pub fn clear(&mut self) {
self.path.clear();
self.os = None;
}
#[inline]
pub fn set_from_str(&mut self, s: &str) {
self.path.clear();
self.path.push_str(s);
self.os = None;
}
pub fn set_from_os(&mut self, p: &Path) {
let os = p.as_os_str();
self.path.clear();
match os.to_str() {
Some(s) => {
self.path.push_str(s);
self.os = None;
}
None => {
self.path.push_str(&os.to_string_lossy());
self.os = Some(os.to_owned());
}
}
}
#[inline]
pub fn as_path(&self) -> &Path {
match &self.os {
Some(os) => Path::new(os),
None => Path::new(&self.path),
}
}
#[cfg(unix)]
#[inline]
pub fn as_bytes(&self) -> &[u8] {
use std::os::unix::ffi::OsStrExt;
match &self.os {
Some(os) => os.as_bytes(),
None => self.path.as_bytes(),
}
}
#[cfg(windows)]
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.path.as_bytes()
}
#[inline]
pub fn as_printable_string(&self) -> &str {
&self.path
}
#[inline]
pub fn is_lossless(&self) -> bool {
self.os.is_none()
}
}
impl std::fmt::Debug for ContentPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_lossless() {
write!(f, "ContentPath({:?})", self.path)
} else {
write!(f, "ContentPath({:?}, lossy)", self.path)
}
}
}
pub trait IntoContentPath {
fn into_content_path(self) -> ContentPath;
}
impl IntoContentPath for &str {
#[inline]
fn into_content_path(self) -> ContentPath { ContentPath::from_str(self) }
}
impl IntoContentPath for &Path {
#[inline]
fn into_content_path(self) -> ContentPath { ContentPath::from_os(self) }
}
impl IntoContentPath for ContentPath {
#[inline]
fn into_content_path(self) -> ContentPath { self }
}