use std::ffi::OsString;
use std::path::{Path, PathBuf};
#[derive(Default)]
pub struct ContentPath {
path: String,
os: Option<OsString>,
}
impl ContentPath {
#[inline(always)]
#[allow(clippy::should_implement_trait)]
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 From<&str> for ContentPath {
fn from(s: &str) -> Self {
Self::from_str(s)
}
}
impl From<String> for ContentPath {
fn from(s: String) -> Self {
Self::with_string(s)
}
}
impl From<&String> for ContentPath {
fn from(s: &String) -> Self {
Self::from_str(s)
}
}
impl From<&Path> for ContentPath {
fn from(p: &Path) -> Self {
Self::from_os(p)
}
}
impl From<PathBuf> for ContentPath {
fn from(p: PathBuf) -> Self {
Self::from_os(&p)
}
}
impl From<&PathBuf> for ContentPath {
fn from(p: &PathBuf) -> Self {
Self::from_os(p)
}
}
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)
}
}
}