### Quick Example Source: https://docs.rs/isomage A quick example demonstrating how to open an ISO file, detect and parse its filesystem, and iterate through the root directory's children. ```APIDOC ## Quick example ```rust use std::fs::File; use isomage::detect_and_parse_filesystem; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; for child in &root.children { let kind = if child.is_directory { "d" } else { "-" }; println!("{} {} ({} bytes)", kind, child.name, child.size); } ``` ``` -------------------------------- ### Quick Example: Browsing ISO Image Contents Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Demonstrates how to open an ISO file, parse its filesystem, and iterate through the root directory's children to display their type, name, and size. This example requires a file named 'disc.iso' to exist. ```rust use std::fs::File; use isomage::detect_and_parse_filesystem; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; for child in &root.children { let kind = if child.is_directory { "d" } else { "-" }; println!("{} {} ({} bytes)", kind, child.name, child.size); } # Ok::<(), isomage::Error>(()) ``` -------------------------------- ### Clone From Example for Box Source: https://docs.rs/isomage/latest/isomage/type.Error.html Demonstrates using clone_from to copy contents into an existing Box without new allocation. ```rust let x = Box::new(5); let mut y = Box::new(10); let yp: *const i32 = &*y; y.clone_from(&x); // The value is the same assert_eq!(x, y); // And no allocation occurred assert_eq!(yp, &*y); ``` -------------------------------- ### Clone Example for Box Source: https://docs.rs/isomage/latest/isomage/type.Error.html Demonstrates cloning a Box and verifying that the values are the same but the objects are unique. ```rust let x = Box::new(5); let y = x.clone(); // The value is the same assert_eq!(x, y); // But they are unique objects assert_ne!(&*x as *const i32, &*y as *const i32); ``` -------------------------------- ### Example Usage of cat_node Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Demonstrates how to open an ISO file, parse it to find a specific file node, and then use `cat_node` to extract its content into a buffer. ```rust use std::fs::File; use isomage::{detect_and_parse_filesystem, cat_node}; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; let node = root.find_node("etc/hostname") .ok_or("not in ISO")?; let mut out = Vec::new(); cat_node(&mut file, node, &mut out)?; # Ok::<(), isomage::Error>(()) ``` -------------------------------- ### Demonstration of a poor `From>` impl Source: https://docs.rs/isomage/latest/isomage/type.Error.html This example demonstrates a problematic implementation of `From>` for `Pin` which can lead to ambiguity when calling `Pin::from`. It is not recommended for crates to add such implementations. ```rust struct Foo; impl From> for Pin { fn from(_: Box<()>) -> Pin { Pin::new(Foo) } } let foo = Box::new(()); let bar = Pin::from(foo); ``` -------------------------------- ### Test Module Setup Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Sets up the test module for the isomage library. It imports necessary items from the super module, including file operations and the library's core functionalities. ```rust use super::*; use std::fs::File; ``` -------------------------------- ### Example usage of find_node Source: https://docs.rs/isomage/latest/src/isomage/tree.rs.html Demonstrates how to use the `find_node` method to locate nodes within a directory tree. It shows successful lookups with and without leading slashes, as well as handling of non-existent paths. ```rust use isomage::TreeNode; let mut root = TreeNode::new_directory("/".to_string()); let mut etc = TreeNode::new_directory("etc".to_string()); etc.add_child(TreeNode::new_file("hostname".to_string(), 18)); root.add_child(etc); assert!(root.find_node("etc/hostname").is_some()); assert!(root.find_node("/etc/hostname").is_some()); assert!(root.find_node("etc/missing").is_none()); ``` -------------------------------- ### Recreate Box from NonNull Pointer Source: https://docs.rs/isomage/latest/isomage/type.Error.html This example demonstrates recreating a Box from a NonNull pointer, typically obtained from `Box::into_non_null`. This is a nightly-only feature. ```rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` -------------------------------- ### Recreate Box from Raw Pointer Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use this example to recreate a Box from a raw pointer obtained via `Box::into_raw`. Ensure the pointer is valid and was allocated by the global allocator. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Compare Extract vs Cat for Linux ISO File Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Compares the content of 'etc/hosts' from a Linux ISO obtained via extraction with the content obtained via the 'cat_node' function. Requires a parsed Linux ISO and temporary directory setup. ```rust if let Some((mut file, root)) = parse_linux_iso() { let dir = std::env::temp_dir().join("isomage_test_extract_vs_cat"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let node = root.find_node("etc/hosts").expect("etc/hosts not found"); let mut cat_output = Vec::new(); cat_node(&mut file, node, &mut cat_output).expect("cat failed"); extract_node(&mut file, node, dir.to_str().unwrap()).expect("extract failed"); let extracted = std::fs::read(dir.join("hosts")).unwrap(); assert_eq!( cat_output, extracted, ); std::fs::remove_dir_all(&dir).ok(); } ``` -------------------------------- ### Into Ok Value (Never Panics) Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `into_ok` to get the contained `Ok` value without panicking. This is an experimental API that guarantees no panics. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Convert Box to raw pointer and recreate with Box::from_raw_in Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use Box::into_raw_with_allocator to consume a Box and get a raw pointer and the allocator. Then, use Box::from_raw_in to recreate the Box, allowing its destructor to handle cleanup. ```rust #![feature(allocator_api)] use std::alloc.System; let x = Box::new_in(String::from("Hello"), System); let (ptr, alloc) = Box::into_raw_with_allocator(x); let x = unsafe { Box::from_raw_in(ptr, alloc) }; ``` -------------------------------- ### Test Extract Directory from Linux ISO Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Extracts the 'etc' directory from a Linux ISO to a temporary location, verifying that both 'hostname' and 'hosts' files are present and that 'hostname' contains the expected content. Requires a parsed Linux ISO and temporary directory setup. ```rust if let Some((mut file, root)) = parse_linux_iso() { let dir = std::env::temp_dir().join("isomage_test_extract_dir"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let node = root.find_node("etc").expect("etc not found"); extract_node(&mut file, node, dir.to_str().unwrap()).expect("extract failed"); assert!(dir.join("etc/hostname").exists(), "hostname should exist"); assert!(dir.join("etc/hosts").exists(), "hosts should exist"); let hostname = std::fs::read_to_string(dir.join("etc/hostname")).unwrap(); assert!(hostname.contains("test-linux-system")); std::fs::remove_dir_all(&dir).ok(); } ``` -------------------------------- ### Convert Box to NonNull pointer and recreate with Box::from_non_null_in Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use Box::into_non_null_with_allocator to consume a Box and get a NonNull pointer and the allocator. Then, use Box::from_non_null_in to recreate the Box for automatic cleanup. ```rust #![feature(allocator_api)] use std::alloc.System; let x = Box::new_in(String::from("Hello"), System); let (non_null, alloc) = Box::into_non_null_with_allocator(x); let x = unsafe { Box::from_non_null_in(non_null, alloc) }; ``` -------------------------------- ### Test Extract Single File from Linux ISO Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Extracts a single file ('etc/hostname') from a Linux ISO to a temporary directory and verifies its content. Requires a parsed Linux ISO and temporary directory setup. ```rust if let Some((mut file, root)) = parse_linux_iso() { let dir = std::env::temp_dir().join("isomage_test_extract_single"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let node = root .find_node("etc/hostname") .expect("etc/hostname not found"); extract_node(&mut file, node, dir.to_str().unwrap()).expect("extract failed"); let extracted = std::fs::read_to_string(dir.join("hostname")).unwrap(); assert!(extracted.contains("test-linux-system")); std::fs::remove_dir_all(&dir).ok(); } ``` -------------------------------- ### Test Extract Root Directory from Linux ISO Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Extracts the entire root of a Linux ISO to a temporary directory, verifying the existence of top-level directories and a deep file ('home/user/.bashrc'). Requires a parsed Linux ISO and temporary directory setup. ```rust if let Some((mut file, root)) = parse_linux_iso() { let dir = std::env::temp_dir().join("isomage_test_extract_root"); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); extract_node(&mut file, &root, dir.to_str().unwrap()).expect("extract root failed"); for name in &["boot", "etc", "home", "usr", "var"] { assert!(dir.join(name).is_dir(), "{} directory should exist", name); } assert!( dir.join("home/user/.bashrc").exists(), ".bashrc should exist" ); std::fs::remove_dir_all(&dir).ok(); } ``` -------------------------------- ### Stream a file from ISO using cat_node Source: https://docs.rs/isomage/latest/isomage/fn.cat_node.html Use `cat_node` to stream the contents of a specific file within an ISO image to a buffer. This example demonstrates opening the ISO, parsing the filesystem, finding a file node, and then using `cat_node` to copy its content into a `Vec`. ```rust use std::fs::File; use isomage::{detect_and_parse_filesystem, cat_node}; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; let node = root.find_node("etc/hostname") .ok_or("not in ISO")?; let mut out = Vec::new(); cat_node(&mut file, node, &mut out)?; ``` -------------------------------- ### Get Raw Pointer to Box Contents (Nightly) Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::as_ptr` to get a raw pointer to the Box's contents. The caller must ensure the Box outlives the pointer and that the memory is not written to via this pointer. This method is safe for aliasing models. ```rust #![feature(box_as_ptr)] unsafe { let mut v = Box::new(0); let ptr1 = Box::as_ptr(&v); let ptr2 = Box::as_mut_ptr(&mut v); let _val = ptr2.read(); // No write to this memory has happened yet, so `ptr1` is still valid. let _val = ptr1.read(); // However, once we do a write... ptr2.write(1); // ... `ptr1` is no longer valid. // This would be UB: let _val = ptr1.read(); } ``` -------------------------------- ### Get Stream Position Source: https://docs.rs/isomage/latest/isomage/type.Error.html Returns the current position within the stream. ```APIDOC ## fn stream_position(&mut self) -> Result ### Description Returns the current seek position from the start of the stream. ### Method `stream_position` ### Parameters None ### Request Example None ### Response #### Success Response (200) - `u64`: The current position in the stream. #### Response Example None ### Error Handling - `Error`: If an error occurs while determining the stream position. ``` -------------------------------- ### fn try_rfold Source: https://docs.rs/isomage/latest/isomage/type.Error.html This is the reverse version of `Iterator::try_fold()`: it takes elements starting from the back of the iterator. ```APIDOC ## fn try_rfold ### Description This is the reverse version of `Iterator::try_fold()`: it takes elements starting from the back of the iterator. ### Parameters * `init`: B - The initial value. * `f`: F - The closure to apply to the elements. ### Type Parameters * `B`: The type of the initial value and the result. * `F`: The type of the closure. * `R`: The type of the `Try` result. ### Returns R - The result of the fold operation. ``` -------------------------------- ### Get Stream Length (Nightly) Source: https://docs.rs/isomage/latest/isomage/type.Error.html Returns the total length of the stream in bytes. This is a nightly-only experimental API. ```APIDOC ## fn stream_len(&mut self) -> Result ### Description Returns the length of this stream (in bytes). This is a nightly-only experimental API. ### Method `stream_len` ### Parameters None ### Request Example None ### Response #### Success Response (200) - `u64`: The length of the stream in bytes. #### Response Example None ### Error Handling - `Error`: If an error occurs while determining the stream length. ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/isomage/latest/isomage/type.Error.html Constructs a new box with uninitialized contents on the heap. ```APIDOC ## Box::new_uninit ### Description Constructs a new box with uninitialized contents on the heap. ### Method `Box::new_uninit() -> Box>` ### Parameters None ### Request Example ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ### Response #### Success Response (200) Returns a `Box>` with uninitialized contents. #### Response Example None ``` -------------------------------- ### fn rfold Source: https://docs.rs/isomage/latest/isomage/type.Error.html An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. ```APIDOC ## fn rfold ### Description An iterator method that reduces the iterator’s elements to a single, final value, starting from the back. ### Parameters * `init`: B - The initial value. * `f`: F - The closure to apply to the elements. ### Type Parameters * `B`: The type of the initial value and the result. * `F`: The type of the closure. ### Returns B - The final reduced value. ``` -------------------------------- ### Read Partition Descriptor Source: https://docs.rs/isomage/latest/src/isomage/udf.rs.html Reads a Partition Descriptor from a UDF file. Use this to identify partition numbers and their starting sectors. ```rust let mut vds_buffer = vec![0u8; SECTOR_SIZE as usize]; file.read_exact(&mut vds_buffer)?; let vds_tag_id = u16::from_le_bytes([vds_buffer[0], vds_buffer[1]]); match vds_tag_id { 5 => { // Partition Descriptor let part_num = u16::from_le_bytes([vds_buffer[22], vds_buffer[23]]); let part_start = u32::from_le_bytes([ vds_buffer[188], vds_buffer[189], vds_buffer[190], vds_buffer[191], ]) as u64; if verbose { eprintln!( " Found Partition Descriptor #%d: starts at sector %d", part_num, part_start ); } partitions.push(PartitionInfo { number: part_num, start_sector: part_start, }); } 6 => { // Logical Volume Descriptor // FSD location at offset 248 root_fsd_long_ad = Some(read_long_ad(&vds_buffer[248..264])); if verbose { let ad = root_fsd_long_ad.unwrap(); eprintln!( " Found Logical Volume Descriptor. FSD at location %d in partition %d", ad.location, ad.partition ); } // Parse partition maps to find metadata partition let map_table_length = u32::from_le_bytes([ vds_buffer[264], vds_buffer[265], vds_buffer[266], vds_buffer[267], ]) as usize; let num_partition_maps = u32::from_le_bytes([ vds_buffer[268], vds_buffer[269], vds_buffer[270], vds_buffer[271], ]); if verbose { eprintln!( " %d partition maps, table length %d bytes", num_partition_maps, map_table_length ); } // Partition maps start at offset 440 let mut map_offset = 440usize; for map_idx in 0..num_partition_maps { if map_offset + 2 > vds_buffer.len() { break; } let map_type = vds_buffer[map_offset]; let map_length = vds_buffer[map_offset + 1] as usize; if map_length == 0 { break; } // malformed map: avoid infinite loop if verbose { eprintln!( " Partition map %d: type %d, length %d", map_idx, map_type, map_length ); } if map_type == 2 && map_length >= 64 { let id_string = &vds_buffer[map_offset + 5..map_offset + 28]; if verbose { let id_printable: String = id_string .iter() .take_while(|&&b| b != 0) .map(|&b| { if (0x20..0x7f).contains(&b) { b as char } else { '.' } }) .collect(); eprintln!(" Type 2 identifier: '%s'", id_printable); } if id_string.starts_with(b"*UDF Metadata Partition") { let meta_part_ref = u16::from_le_bytes([ vds_buffer[map_offset + 38], vds_buffer[map_offset + 39], ]); let meta_file_loc = u32::from_le_bytes([ vds_buffer[map_offset + 40], vds_buffer[map_offset + 41], vds_buffer[map_offset + 42], vds_buffer[map_offset + 43], ]); if verbose { eprintln!( ``` -------------------------------- ### Create By Reference Adapter for Write Source: https://docs.rs/isomage/latest/isomage/type.Error.html Creates a "by reference" adapter for the current Write instance. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Write`. ### Method `by_ref` ### Parameters None ### Request Example None ### Response - `&mut Self`: A mutable reference to the adapter. ``` -------------------------------- ### Manually create Box from scratch Source: https://docs.rs/isomage/latest/isomage/type.Error.html Manually allocate memory using the system allocator and then create a Box from the raw pointer. Ensure to write the value and handle deallocation correctly. ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### Into Err Value (Never Panics) Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `into_err` to get the contained `Err` value without panicking. This is an experimental API that guarantees no panics. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Create a zero-initialized Box Source: https://docs.rs/isomage/latest/isomage/type.Error.html Demonstrates creating a Box with zero-initialized memory using `try_new_zeroed`. This requires the `allocator_api` feature. ```rust #![feature(allocator_api)] let zero = Box::::try_new_zeroed()?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Create a new directory node Source: https://docs.rs/isomage/latest/isomage/tree/struct.TreeNode.html Constructs an empty directory node. The `size` field will be 0 until `calculate_directory_size` is called. ```rust pub fn new_directory(name: String) -> Self ``` -------------------------------- ### Manually create a Box from raw pointer and system allocator Source: https://docs.rs/isomage/latest/isomage/type.Error.html Demonstrates manually creating a Box from a raw pointer obtained via the system allocator. This involves allocating memory, writing the value, and then constructing the Box using `Box::from_raw_in`. This requires `allocator_api` and `slice_ptr_get` features and is inherently unsafe. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Consume Box and get inner value Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::into_inner` to consume a `Box` and retrieve the value it contains. This operation moves the value out of the box. ```rust #![feature(box_into_inner)] let c = Box::new(5); assert_eq!(Box::into_inner(c), 5); ``` -------------------------------- ### Parse ISO/UDF and list directory contents Source: https://docs.rs/isomage Opens an ISO/UDF image file, detects and parses the filesystem, and then iterates through the root directory's children, printing their type, name, and size. Requires `std::fs::File` and `isomage::detect_and_parse_filesystem`. ```rust use std::fs::File; use isomage::detect_and_parse_filesystem; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; for child in &root.children { let kind = if child.is_directory { "d" } else { "-" }; println!("{} {} ({} bytes)", kind, child.name, child.size); } ``` -------------------------------- ### Manual Cleanup Equivalent using Box::from_raw Source: https://docs.rs/isomage/latest/isomage/type.Error.html This demonstrates an equivalent manual cleanup process by converting the raw pointer back to a `Box` and then explicitly dropping that `Box`. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); unsafe { drop(Box::from_raw(ptr)); } ``` -------------------------------- ### Unwrap a Result Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `unwrap` to get the contained `Ok` value. Panics if the value is an `Err`, with a panic message provided by the `Err`’s value. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Test Linux ISO expected directories Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Verifies that specific expected directories exist within the root of a parsed Linux ISO. Asserts that each found entry is indeed a directory. ```rust #[test] fn test_linux_iso_expected_directories() { if let Some((_file, root)) = parse_linux_iso() { for dir_name in &["boot", "etc", "home", "usr", "var"] { let node = root .find_node(dir_name) .unwrap_or_else(|| panic!("Expected directory '{}' not found", dir_name)); assert!(node.is_directory, "'{}' should be a directory", dir_name); } } } ``` -------------------------------- ### Get references to Result values Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `as_ref()` to obtain a `Result<&T, &E>` from a `&Result`. This allows inspecting the contents of a `Result` without consuming it. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Box::new_uninit_in Source: https://docs.rs/isomage/latest/isomage/type.Error.html Constructs a new box with uninitialized contents in the provided allocator. ```APIDOC ## Box::new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator. ### Method `pub fn new_uninit_in(alloc: A) -> Box, A>` ### Parameters - **alloc** (A) - The allocator to use. ### Request Example ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` ``` -------------------------------- ### Unwrap or Default for Result Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `unwrap_or_default` to get the contained `Ok` value or a default value if it's an `Err`. Requires the `Ok` type to implement `Default`. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Read Extent AD Source: https://docs.rs/isomage/latest/src/isomage/udf.rs.html Reads an Extent Address Descriptor (AD) from a buffer. This structure describes a file's extent, including its length and starting location. ```rust fn read_extent_ad(buffer: &[u8]) -> ExtentAd { ExtentAd { length: u32::from_le_bytes([buffer[0], buffer[1], buffer[2], buffer[3]]), location: u32::from_le_bytes([buffer[4], buffer[5], buffer[6], buffer[7]]), } } ``` -------------------------------- ### Construct an empty directory node Source: https://docs.rs/isomage/latest/src/isomage/tree.rs.html Creates a new directory node. The `size` is initialized to 0 and will be updated later by `calculate_directory_size` if needed. ```rust pub fn new_directory(name: String) -> Self { Self { name, size: 0, is_directory: true, children: Vec::new(), file_location: None, file_length: None, } } ``` -------------------------------- ### Unwrap Error from Result Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `unwrap_err` to get the contained `Err` value. Panics if the value is an `Ok`, with a custom panic message provided by the `Ok`’s value. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Handling File Metadata with `Result` Source: https://docs.rs/isomage/latest/isomage/type.Result.html Illustrates using `Result` for file system operations, specifically retrieving metadata. It shows how to handle both successful retrieval of metadata and cases where the path is invalid, resulting in an `Err`. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Expect Error on Result Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `expect_err` to get the contained `Err` value. Panics if the value is an `Ok`, with a panic message including the passed message and the content of the `Ok`. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### Box::new Source: https://docs.rs/isomage/latest/isomage/type.Error.html Allocates memory on the heap and places the given value into it. ```APIDOC ## Box::new ### Description Allocates memory on the heap and then places `x` into it. This doesn’t actually allocate if `T` is zero-sized. ### Method `Box::new(x: T) -> Box` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let five = Box::new(5); ``` ### Response #### Success Response (200) Returns a `Box` containing the value `x`. #### Response Example None ``` -------------------------------- ### Unwrapping with a Default Value using `unwrap_or` Source: https://docs.rs/isomage/latest/isomage/type.Result.html Shows how to get the `Ok` value from a `Result` or use a provided default value if the `Result` is `Err`. The default value is eagerly evaluated. ```rust let default = 2; let x: Result = Ok(9); assert_eq!(x.unwrap_or(default), 9); let x: Result = Err("error"); assert_eq!(x.unwrap_or(default), default); ``` -------------------------------- ### Box::clone_from_ref Source: https://docs.rs/isomage/latest/isomage/type.Error.html Allocates memory on the heap then clones the source reference into it. This is a nightly-only experimental API. ```APIDOC ## Box::clone_from_ref ### Description Allocates memory on the heap then clones `src` into it. This doesn’t actually allocate if `src` is zero-sized. ### Method Associated function (called as `Box::clone_from_ref(src)`) ### Parameters - **src** (&T) - The reference to clone. ### Response - **Box** - A new box containing a clone of `src`. ### Request Example ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` ``` -------------------------------- ### Get mutable references to Result values Source: https://docs.rs/isomage/latest/isomage/type.Result.html Use `as_mut()` to obtain a `Result<&mut T, &mut E>` from a `&mut Result`. This allows modifying the contents of a `Result` in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Box::try_new_uninit Source: https://docs.rs/isomage/latest/isomage/type.Error.html Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. ```APIDOC ## Box::try_new_uninit ### Description Constructs a new box with uninitialized contents on the heap, returning an error if the allocation fails. ### Method `Box::try_new_uninit() -> Result>, AllocError>` ### Parameters None ### Request Example ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ### Response #### Success Response (200) Returns a `Box>` with uninitialized contents if allocation is successful. #### Error Response (AllocError) Returns an `AllocError` if the allocation fails. #### Response Example None ``` -------------------------------- ### Filesystem Detection and Parsing Source: https://docs.rs/isomage/latest/isomage/all.html Functions to detect and parse ISO9660 and UDF filesystems. Includes verbose options for more detailed output. ```APIDOC ## detect_and_parse_filesystem ### Description Detects and parses the filesystem of a given input. ### Function Signature `fn detect_and_parse_filesystem(...)` ## detect_and_parse_filesystem_verbose ### Description Detects and parses the filesystem of a given input with verbose output. ### Function Signature `fn detect_and_parse_filesystem_verbose(...)` ## iso9660::parse_iso9660 ### Description Parses an ISO9660 filesystem. ### Function Signature `fn parse_iso9660(...)` ## iso9660::parse_iso9660_verbose ### Description Parses an ISO9660 filesystem with verbose output. ### Function Signature `fn parse_iso9660_verbose(...)` ## udf::parse_udf ### Description Parses a UDF filesystem. ### Function Signature `fn parse_udf(...)` ## udf::parse_udf_verbose ### Description Parses a UDF filesystem with verbose output. ### Function Signature `fn parse_udf_verbose(...)` ``` -------------------------------- ### fn provide Source: https://docs.rs/isomage/latest/isomage/type.Error.html Provides type-based access to context intended for error reports. This is a nightly-only experimental API. ```APIDOC ## fn provide ### Description Provides type-based access to context intended for error reports. ### Parameters * `request`: &'b mut Request<'b> - The request for context. ### Notes This is a nightly-only experimental API. (`error_generic_member_access`) ``` -------------------------------- ### Create By Reference Adapter for Read Source: https://docs.rs/isomage/latest/isomage/type.Error.html Creates a "by reference" adapter for the current Read instance. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Creates a “by reference” adapter for this instance of `Read`. ### Method `by_ref` ### Parameters None ### Request Example None ### Response - `&mut Self`: A mutable reference to the adapter. ``` -------------------------------- ### Test ISO 9660 parsing Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Verifies that ISO 9660 parsing works correctly for both Linux and macOS test ISOs. Asserts that the root directory is named '/' and has children. ```rust #[test] fn test_iso9660_parsing() { for test_file in &["test_linux.iso", "test_macos.iso"] { if let Some(mut file) = require_test_file(test_file) { let root = iso9660::parse_iso9660(&mut file) .unwrap_or_else(|e| panic!("ISO 9660 parsing failed for {}: {}", test_file, e)); assert_eq!(root.name, "/"); assert!(root.is_directory); assert!( !root.children.is_empty(), "{}" should have children", test_file ); } } } ``` -------------------------------- ### Detect and Parse Filesystem (Basic) Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Parses the filesystem contained in a given file, attempting ISO 9660 first, then UDF. It returns the root node of the directory tree. The filename is used only for error messages. ```rust use std::fs::File; use isomage::detect_and_parse_filesystem; let mut file = File::open("disc.iso")?; let root = detect_and_parse_filesystem(&mut file, "disc.iso")?; assert_eq!(root.name, "/"); # Ok::<(), isomage::Error>(()) ``` -------------------------------- ### Box::try_clone_from_ref Source: https://docs.rs/isomage/latest/isomage/type.Error.html Allocates memory on the heap then clones the source reference into it, returning an error if allocation fails. This is a nightly-only experimental API. ```APIDOC ## Box::try_clone_from_ref ### Description Allocates memory on the heap then clones `src` into it, returning an error if allocation fails. This doesn’t actually allocate if `src` is zero-sized. ### Method Associated function (called as `Box::try_clone_from_ref(src)`) ### Parameters - **src** (&T) - The reference to clone. ### Response - **Result, AllocError>** - A `Result` containing a new box if successful, or an `AllocError` if allocation fails. ### Request Example ```rust #![feature(clone_from_ref)] #![feature(allocator_api)] let hello: Box = Box::try_clone_from_ref("hello")?; ``` ``` -------------------------------- ### Safe Path Joining Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Safely joins a parent path with an entry name, ensuring the resulting path does not escape the specified root directory. It first validates the entry name and then checks if the joined path starts with the root. ```rust fn safe_join(root: &Path, here: &Path, name: &str) -> Result { validate_entry_name(name)?; let target = here.join(name); if !target.starts_with(root) { return Err(format!( "path escape: entry '{}' would write outside output directory {}", name, root.display() ) .into()); } Ok(target) } ``` -------------------------------- ### Box::try_new_uninit_in Source: https://docs.rs/isomage/latest/isomage/type.Error.html Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. ```APIDOC ## Box::try_new_uninit_in ### Description Constructs a new box with uninitialized contents in the provided allocator, returning an error if the allocation fails. ### Method `pub fn try_new_uninit_in(alloc: A) -> Result, A>, AllocError>` ### Parameters - **alloc** (A) - The allocator to use. ### Request Example ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` ``` -------------------------------- ### Detect and Parse Filesystem Source: https://docs.rs/isomage/latest/src/isomage/lib.rs.html Attempts to parse the provided file as either ISO 9660 or UDF. It returns the root of the parsed filesystem on success. If both parsing attempts fail, it returns an error detailing the failures. ```rust match iso9660::parse_iso9660_verbose(file, verbose) { Ok(root) => return Ok(root), Err(e) => { if verbose { eprintln!(" ISO 9660 parsing failed: {}", e); } errors.push(format!("ISO 9660: {}", e)); } } // Seek back to start before trying next parser file.seek(SeekFrom::Start(0))?; if verbose { eprintln!("\nAttempting UDF parsing..."); } match udf::parse_udf_verbose(file, verbose) { Ok(root) => return Ok(root), Err(e) => { if verbose { eprintln!(" UDF parsing failed: {}", e); } errors.push(format!("UDF: {}", e)); } } let mut msg = format!("Unable to detect supported filesystem in {}", filename); if !errors.is_empty() { msg.push_str("\nDetails:\n -"); msg.push_str(&errors.join("\n -")); } Err(msg.into()) ``` -------------------------------- ### Sum of Results Source: https://docs.rs/isomage/latest/isomage/type.Result.html Calculates the sum of elements in an iterator where each element is a Result. If any element is an Err, the entire operation returns that Err. Otherwise, it returns the sum of the Ok values. This example demonstrates summing integers, returning an error if a negative number is encountered. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); ``` ```rust let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Create an uninitialized Box with custom allocator Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::new_uninit_in` to construct a `Box` with uninitialized contents using the provided allocator. The contents can be initialized later. This is useful for deferred initialization. ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### Get Mutable Pointer to Box Contents (Nightly) Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::as_mut_ptr` to obtain a raw mutable pointer to the Box's contents. Ensure the Box outlives the pointer to avoid dangling pointers. This method is safe for aliasing models when mixed with `as_ptr`. ```rust #![feature(box_as_ptr)] unsafe { let mut b = Box::new(0); let ptr1 = Box::as_mut_ptr(&mut b); ptr1.write(1); let ptr2 = Box::as_mut_ptr(&mut b); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` -------------------------------- ### Create a new file node with location Source: https://docs.rs/isomage/latest/isomage/tree/struct.TreeNode.html Constructs a file node with its byte-range location and length specified. This is the recommended constructor for parsers creating nodes for actual files. ```rust pub fn new_file_with_location( name: String, size: u64, location: u64, length: u64, ) -> Self ``` -------------------------------- ### Clone a Box from a reference Source: https://docs.rs/isomage/latest/isomage/type.Error.html Demonstrates cloning a string slice into a new Box using `Box::clone_from_ref`. This API is experimental and requires the `clone_from_ref` feature. ```rust #![feature(clone_from_ref)] let hello: Box = Box::clone_from_ref("hello"); ``` -------------------------------- ### Try to create an uninitialized Box with custom allocator Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::try_new_uninit_in` to attempt constructing a `Box` with uninitialized contents using the provided allocator. Returns an error if allocation fails. Deferred initialization is supported. ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### into_ok Source: https://docs.rs/isomage/latest/isomage/type.Result.html Returns the contained Ok value, but never panics. This is an experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for, making it a maintainability safeguard. ### Method `into_ok()` ### Constraints Requires `E: Into`. ### Note This is a nightly-only experimental API. ### Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ``` -------------------------------- ### Manual Cleanup Equivalent using Box::from_non_null Source: https://docs.rs/isomage/latest/isomage/type.Error.html This demonstrates an equivalent manual cleanup process by converting the `NonNull` pointer back to a `Box` and then explicitly dropping that `Box`. ```rust #![feature(box_vec_non_null)] let x = Box::new(String::from("Hello")); let non_null = Box::into_non_null(x); unsafe { drop(Box::from_non_null(non_null)); } ``` -------------------------------- ### Box::try_new Source: https://docs.rs/isomage/latest/isomage/type.Error.html Allocates memory on the heap then places x into it, returning an error if the allocation fails. ```APIDOC ## Box::try_new ### Description Allocates memory on the heap then places `x` into it, returning an error if the allocation fails. ### Method `Box::try_new(x: T) -> Result, AllocError>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust #![feature(allocator_api)] let five = Box::try_new(5)?; ``` ### Response #### Success Response (200) Returns a `Box` containing the value `x` if allocation is successful. #### Error Response (AllocError) Returns an `AllocError` if the allocation fails. #### Response Example None ``` -------------------------------- ### take Source: https://docs.rs/isomage/latest/isomage/type.Error.html Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ```APIDOC ## take(self, n: usize) ### Description Creates an iterator that yields the first `n` elements, or fewer if the underlying iterator ends sooner. ### Method `take` ### Parameters - **n** (usize) - Description: The maximum number of elements to yield. ``` -------------------------------- ### Try to create a zeroed Box with custom allocator Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use `Box::try_new_zeroed_in` to attempt constructing a `Box` with uninitialized contents, filled with `0` bytes by the specified allocator. Returns an error if allocation fails. ```rust #![feature(allocator_api)] use std::alloc::System; let zero = Box::::try_new_zeroed_in(System)?; let zero = unsafe { zero.assume_init() }; assert_eq!(*zero, 0); ``` -------------------------------- ### Attempt to Construct Box with Uninitialized Contents using try_new_uninit Source: https://docs.rs/isomage/latest/isomage/type.Error.html Use the experimental `Box::try_new_uninit` to attempt creating a `Box` with uninitialized memory. It returns a `Result` which is `Ok(Box>)` on success or `Err(AllocError)` if the allocation fails. ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ```