VirtualRoot

Struct VirtualRoot 

Source
pub struct VirtualRoot<Marker = ()> { /* private fields */ }
Expand description

SUMMARY: Provide a user‑facing virtual root that produces VirtualPath values clamped to a boundary.

Implementations§

Source§

impl<Marker> VirtualRoot<Marker>

Source

pub fn try_new<P: AsRef<Path>>(root_path: P) -> Result<Self>

SUMMARY: Create a VirtualRoot from an existing directory.

PARAMETERS:

  • root_path (AsRef<Path>): Existing directory to anchor the virtual root.

RETURNS:

  • Result<VirtualRoot<Marker>>: New virtual root with clamped operations.

ERRORS:

  • StrictPathError::InvalidRestriction: Root invalid or cannot be canonicalized.

EXAMPLE: Uses AsRef<Path> for maximum ergonomics, including direct TempDir support for clean shadowing patterns:

use strict_path::VirtualRoot;
let tmp_dir = tempfile::tempdir()?;
let tmp_dir = VirtualRoot::<()>::try_new(tmp_dir)?; // Clean variable shadowing
Source

pub fn try_new_temp() -> Result<Self>

SUMMARY: Create a VirtualRoot backed by a unique temporary directory with RAII cleanup.

§Example
use strict_path::VirtualRoot;

let uploads_root = VirtualRoot::<()>::try_new_temp()?;
let tenant_file = uploads_root.virtual_join("tenant/document.pdf")?;
let display = tenant_file.virtualpath_display().to_string();
assert!(display.starts_with("/"));
Source

pub fn try_new_temp_with_prefix(prefix: &str) -> Result<Self>

SUMMARY: Create a VirtualRoot in a temporary directory with a custom prefix and RAII cleanup.

§Example
use strict_path::VirtualRoot;

let session_root = VirtualRoot::<()>::try_new_temp_with_prefix("session")?;
let export_path = session_root.virtual_join("exports/report.txt")?;
let display = export_path.virtualpath_display().to_string();
assert!(display.starts_with("/exports"));
Source

pub fn metadata(&self) -> Result<Metadata>

SUMMARY: Return filesystem metadata for the underlying root directory.

Source

pub fn into_virtualpath(self) -> Result<VirtualPath<Marker>>

SUMMARY: Consume this virtual root and return the rooted VirtualPath (“/”).

PARAMETERS:

  • none

RETURNS:

  • Result<VirtualPath<Marker>>: Virtual root path clamped to this boundary.

ERRORS:

  • StrictPathError::PathResolutionError: Canonicalization fails (root removed or inaccessible).
  • StrictPathError::PathEscapesBoundary: Root moved outside the boundary between checks.

EXAMPLE:

let vroot: VirtualRoot = VirtualRoot::try_new(&root)?;
let root_virtual: VirtualPath = vroot.into_virtualpath()?;
assert_eq!(root_virtual.virtualpath_display().to_string(), "/");
Source

pub fn change_marker<NewMarker>(self) -> VirtualRoot<NewMarker>

SUMMARY: Consume this virtual root and substitute a new marker type.

DETAILS: Mirrors crate::PathBoundary::change_marker, crate::StrictPath::change_marker, and crate::VirtualPath::change_marker. Use this when encoding proven authorization into the type system (e.g., after validating a user’s permissions). The consumption makes marker changes explicit during code review.

PARAMETERS:

  • NewMarker (type parameter): Marker to associate with the virtual root.

RETURNS:

  • VirtualRoot<NewMarker>: Same underlying root, rebranded with NewMarker.

EXAMPLE:

struct UserFiles;
struct ReadOnly;
struct ReadWrite;

let read_root: VirtualRoot<(UserFiles, ReadOnly)> = VirtualRoot::try_new(&root_dir)?;

// After authorization check...
let write_root: VirtualRoot<(UserFiles, ReadWrite)> = read_root.change_marker();

SUMMARY: Create a symbolic link at link_path pointing to this root’s underlying directory.

SUMMARY: Create a hard link at link_path pointing to this root’s underlying directory.

Source

pub fn read_dir(&self) -> Result<ReadDir>

SUMMARY: Read directory entries at the virtual root (discovery). Re‑join names through virtual/strict APIs before I/O.

Source

pub fn remove_dir(&self) -> Result<()>

SUMMARY: Remove the underlying root directory (non‑recursive); fails if not empty.

Source

pub fn remove_dir_all(&self) -> Result<()>

SUMMARY: Recursively remove the underlying root directory and all its contents.

Source

pub fn try_new_create<P: AsRef<Path>>(root_path: P) -> Result<Self>

SUMMARY: Ensure the directory exists (create if missing), then return a VirtualRoot.

EXAMPLE: Uses AsRef<Path> for maximum ergonomics, including direct TempDir support for clean shadowing patterns:

use strict_path::VirtualRoot;
let tmp_dir = tempfile::tempdir()?;
let tmp_dir = VirtualRoot::<()>::try_new_create(tmp_dir)?; // Clean variable shadowing
Source

pub fn virtual_join<P: AsRef<Path>>( &self, candidate_path: P, ) -> Result<VirtualPath<Marker>>

SUMMARY: Join a candidate path to this virtual root, producing a clamped VirtualPath.

DETAILS: This is the security gateway for virtual paths. Absolute paths (starting with "/") are automatically clamped to the virtual root, ensuring paths cannot escape the sandbox. For example, "/etc/config" becomes vroot/etc/config, and traversal attempts like "../../../../etc/passwd" are clamped to vroot/etc/passwd. This clamping behavior is what makes the virtual_ dimension safe for user-facing operations.

PARAMETERS:

  • candidate_path (AsRef<Path>): Virtual path to resolve and clamp. Absolute paths are interpreted relative to the virtual root, not the system root.

RETURNS:

  • Result<VirtualPath<Marker>>: Clamped, validated path within the virtual root.

ERRORS:

  • StrictPathError::PathResolutionError, StrictPathError::PathEscapesBoundary.

EXAMPLE:

let vroot: VirtualRoot = VirtualRoot::try_new_create(td.path())?;

// Absolute paths are clamped to virtual root, not system root
let path1 = vroot.virtual_join("/etc/config")?;
assert_eq!(path1.virtualpath_display().to_string(), "/etc/config");

// Traversal attempts are also clamped
let path2 = vroot.virtual_join("../../../etc/passwd")?;
assert_eq!(path2.virtualpath_display().to_string(), "/etc/passwd");

// Both paths are safely within the virtual root on the actual filesystem
Source

pub fn interop_path(&self) -> &OsStr

SUMMARY: Return the virtual root path as &OsStr for unavoidable third-party AsRef<Path> interop.

Source

pub fn exists(&self) -> bool

Returns true if the underlying path boundary root exists.

Source

pub fn as_unvirtual(&self) -> &PathBoundary<Marker>

SUMMARY: Borrow the underlying PathBoundary.

Source

pub fn unvirtual(self) -> PathBoundary<Marker>

SUMMARY: Consume this VirtualRoot and return the underlying PathBoundary (symmetry with virtualize).

Source

pub fn try_new_os_config(app_name: &str) -> Result<Self>

Creates a virtual root in the OS standard config directory.

Cross-Platform Behavior:

  • Linux: ~/.config/{app_name} (XDG Base Directory Specification)
  • Windows: %APPDATA%\{app_name} (Known Folder API - Roaming AppData)
  • macOS: ~/Library/Application Support/{app_name} (Apple Standard Directories)
Source

pub fn try_new_os_data(app_name: &str) -> Result<Self>

Creates a virtual root in the OS standard data directory.

Source

pub fn try_new_os_cache(app_name: &str) -> Result<Self>

Creates a virtual root in the OS standard cache directory.

Source

pub fn try_new_os_config_local(app_name: &str) -> Result<Self>

Creates a virtual root in the OS local config directory.

Source

pub fn try_new_os_data_local(app_name: &str) -> Result<Self>

Creates a virtual root in the OS local data directory.

Source

pub fn try_new_os_home() -> Result<Self>

Creates a virtual root in the user’s home directory.

Source

pub fn try_new_os_desktop() -> Result<Self>

Creates a virtual root in the user’s desktop directory.

Source

pub fn try_new_os_documents() -> Result<Self>

Creates a virtual root in the user’s documents directory.

Source

pub fn try_new_os_downloads() -> Result<Self>

Creates a virtual root in the user’s downloads directory.

Source

pub fn try_new_os_pictures() -> Result<Self>

Creates a virtual root in the user’s pictures directory.

Source

pub fn try_new_os_audio() -> Result<Self>

Creates a virtual root in the user’s music/audio directory.

Source

pub fn try_new_os_videos() -> Result<Self>

Creates a virtual root in the user’s videos directory.

Source

pub fn try_new_os_executables() -> Result<Self>

Creates a virtual root in the OS executable directory (Linux only).

Source

pub fn try_new_os_runtime() -> Result<Self>

Creates a virtual root in the OS runtime directory (Linux only).

Source

pub fn try_new_os_state(app_name: &str) -> Result<Self>

Creates a virtual root in the OS state directory (Linux only).

Source

pub fn try_new_app_path<P: AsRef<Path>>( subdir: P, env_override: Option<&str>, ) -> Result<Self>

SUMMARY: Create a virtual root using the app-path strategy (portable app‑relative directory), optionally honoring an environment variable override.

PARAMETERS:

  • subdir (AsRef<Path>): Subdirectory path relative to the executable location (or to the directory specified by the environment override). Accepts any path‑like value via AsRef<Path>.
  • env_override (Option<&str>): Optional environment variable name to check first; when set and the variable is present, its value is used as the root base instead of the executable directory.

RETURNS:

  • Result<VirtualRoot<Marker>>: Virtual root whose underlying PathBoundary is created if missing and proven safe; all subsequent virtual_join operations are clamped to this root.

ERRORS:

  • StrictPathError::InvalidRestriction: If app-path resolution fails or the directory cannot be created/validated.

EXAMPLE:

use strict_path::VirtualRoot;

// Create ./data relative to the executable (portable layout)
let vroot = VirtualRoot::<()>::try_new_app_path("data", None)?;
let vp = vroot.virtual_join("docs/report.txt")?;
assert_eq!(vp.virtualpath_display().to_string(), "/docs/report.txt");

// With environment override: respects MYAPP_DATA_DIR when set
let _vroot = VirtualRoot::<()>::try_new_app_path("data", Some("MYAPP_DATA_DIR"))?;
Source

pub fn try_new_app_path_with_env<P: AsRef<Path>>( subdir: P, env_override: &str, ) -> Result<Self>

SUMMARY: Create a virtual root via app-path, always consulting a specific environment variable before falling back to the executable‑relative directory.

PARAMETERS:

  • subdir (AsRef<Path>): Subdirectory path used with app-path resolution.
  • env_override (&str): Environment variable name to check first for the root base.

RETURNS:

  • Result<VirtualRoot<Marker>>: New virtual root anchored using app-path semantics.

ERRORS:

  • StrictPathError::InvalidRestriction: If resolution fails or the directory can’t be created/validated.

EXAMPLE:

use strict_path::VirtualRoot;
let _vroot = VirtualRoot::<()>::try_new_app_path_with_env("cache", "MYAPP_CACHE_DIR")?;

Trait Implementations§

Source§

impl<Marker> AsRef<Path> for VirtualRoot<Marker>

Source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<Marker: Clone> Clone for VirtualRoot<Marker>

Source§

fn clone(&self) -> VirtualRoot<Marker>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Marker> Debug for VirtualRoot<Marker>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Marker> Display for VirtualRoot<Marker>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Marker: Default> FromStr for VirtualRoot<Marker>

Source§

fn from_str(path: &str) -> Result<Self, Self::Err>

Parse a VirtualRoot from a string path for universal ergonomics.

Creates the directory if it doesn’t exist, enabling seamless integration with any string-parsing context (clap, config files, environment variables, etc.):

let temp_dir = tempfile::tempdir()?;
let virtual_path = temp_dir.path().join("virtual_dir");
let vroot: VirtualRoot<()> = virtual_path.to_string_lossy().parse()?;
assert!(virtual_path.exists());
Source§

type Err = StrictPathError

The associated error which can be returned from parsing.
Source§

impl<Marker> Hash for VirtualRoot<Marker>

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<Marker> Ord for VirtualRoot<Marker>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<Marker> PartialEq<&Path> for VirtualRoot<Marker>

Source§

fn eq(&self, other: &&Path) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Marker> PartialEq<Path> for VirtualRoot<Marker>

Source§

fn eq(&self, other: &Path) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<M1, M2> PartialEq<PathBoundary<M2>> for VirtualRoot<M1>

Source§

fn eq(&self, other: &PathBoundary<M2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Marker> PartialEq<PathBuf> for VirtualRoot<Marker>

Source§

fn eq(&self, other: &PathBuf) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<M1, M2> PartialEq<VirtualRoot<M2>> for PathBoundary<M1>

Available on crate feature virtual-path only.
Source§

fn eq(&self, other: &VirtualRoot<M2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<M1, M2> PartialEq<VirtualRoot<M2>> for VirtualRoot<M1>

Source§

fn eq(&self, other: &VirtualRoot<M2>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Marker> PartialOrd<&Path> for VirtualRoot<Marker>

Source§

fn partial_cmp(&self, other: &&Path) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Marker> PartialOrd<Path> for VirtualRoot<Marker>

Source§

fn partial_cmp(&self, other: &Path) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Marker> PartialOrd<PathBuf> for VirtualRoot<Marker>

Source§

fn partial_cmp(&self, other: &PathBuf) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Marker> PartialOrd for VirtualRoot<Marker>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<Marker> Eq for VirtualRoot<Marker>

Auto Trait Implementations§

§

impl<Marker> Freeze for VirtualRoot<Marker>

§

impl<Marker> RefUnwindSafe for VirtualRoot<Marker>
where Marker: RefUnwindSafe,

§

impl<Marker> Send for VirtualRoot<Marker>
where Marker: Send,

§

impl<Marker> Sync for VirtualRoot<Marker>
where Marker: Sync,

§

impl<Marker> Unpin for VirtualRoot<Marker>
where Marker: Unpin,

§

impl<Marker> UnwindSafe for VirtualRoot<Marker>
where Marker: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.