### and_then() example function Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for `and_then` showing a function that returns a `Result` and can be used with `and_then` for control flow. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } ``` -------------------------------- ### is_ok() example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the is_ok method. Returns true if the result is Ok, false if it is Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### is_ok_and() example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the is_ok_and method. Returns true if the result is Ok and the value inside matches a predicate. The last example shows using as_ref() to avoid consuming the value. ```rust let x: Result = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### or method examples Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows how the or method returns the Ok value of self if self is Ok, otherwise returns the provided res. The example covers all four combinations of Ok/Err for self and res. ```rust let x: Result = Ok(2); let y: Result = Err("late error"); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("early error"); let y: Result = Ok(2); assert_eq!(x.or(y), Ok(2)); let x: Result = Err("not a 2"); let y: Result = Err("late error"); assert_eq!(x.or(y), Err("late error")); let x: Result = Ok(2); let y: Result = Ok(100); assert_eq!(x.or(y), Ok(2)); ``` -------------------------------- ### unwrap_or example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows how unwrap_or returns the contained Ok value or a provided default. The example demonstrates both Ok and Err cases. ```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); ``` -------------------------------- ### pub fn get(&mut self, filename: &str) -> Result Source: https://docs.rs/war3parser/latest/war3parser/archive/struct.War3MapW3x.html?search= Opens a file inside the MPQ archive. ```APIDOC ## get ### Description Opens a file inside the MPQ archive. ### Method get ### Signature `pub fn get(&mut self, filename: &str) -> Result` ### Parameters - **filename** (&str) - Required - The name of the file to open. ### Returns - `Result` - The opened file or an error. ``` -------------------------------- ### and_then with Path::metadata example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates using and_then with Result from metadata() to chain fallible operations. The example shows that on Windows, "/" maps to "C:\", and that a non-existent path results in an ErrorKind::NotFound error. ```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); ``` -------------------------------- ### transpose() example for Result, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the transpose method on Result, E>. Converts a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### and_then chaining example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows how to chain fallible operations that may return Err using and_then. The example uses a function sq_then_to_string that is not defined in the snippet, but the pattern is to propagate errors when the result is Err. ```rust assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string())); assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed")); assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number")); ``` -------------------------------- ### ok: convert Result to Option Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates `Result::ok`, which converts a `Result` into an `Option`, returning `Some` for `Ok` and `None` for `Err`. The example shows both cases. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Unwrap Err value without checking with unwrap_err_unchecked Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=std%3A%3Avec Shows how to use `unwrap_err_unchecked` to get the contained `Err` value without checking for `Ok`. The example asserts that the returned value matches the error. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` ``` -------------------------------- ### iter_mut: Mutably iterate over possibly contained value Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows `iter_mut` to get a mutable iterator over the possibly contained value. The example mutates the `Ok` value and asserts the result, and also shows the `Err` case yields `None`. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### as_mut: mutate contained value in place Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates `as_mut` to get mutable references to the contained `Ok` or `Err` value, allowing in-place mutation. The example defines a helper function that modifies the value and shows both `Ok` and `Err` cases. ```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); ``` -------------------------------- ### expect: Recommended message style for environment variables Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows the recommended style for `expect` messages: describe the reason you expect the `Result` to be `Ok`. The example reads an environment variable and panics with a message explaining the expectation. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### pub fn open(path: impl AsRef) -> Result Source: https://docs.rs/war3parser/latest/war3parser/archive/struct.War3MapW3x.html?search= Loads a map from a file path. ```APIDOC ## open ### Description Loads a map from a file path. ### Method open ### Signature `pub fn open(path: impl AsRef) -> Result` ### Parameters - **path** (impl AsRef) - Required - The file path to the map. ### Returns - `Result` - The loaded map or an error. ``` -------------------------------- ### Example for Result::is_err Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=std%3A%3Avec Examples for the is_err method, checking if the result is Err. ```rust let x: Result = Ok(-3); assert_eq!(x.is_err(), false); let x: Result = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### unwrap_err_unchecked undefined behavior example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows that calling unwrap_err_unchecked on an Ok is undefined behavior. The example is provided to illustrate the safety contract. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### W3I Field Initialization Source: https://docs.rs/war3parser/latest/src/war3parser/formats/w3i/mod.rs.html?search=u32+-%3E+bool Initializes optional fields for loading screens, prologue screens, fog, and camera settings. ```rust let mut loading_screen_text = None; let mut loading_screen_title = None; let mut loading_screen_subtitle = None; let mut game_data_set = None; let mut loading_screen_index = None; let mut prologue_screen_model = None; let mut prologue_screen_text = None; let mut prologue_screen_title = None; let mut prologue_screen_subtitle = None; let mut fog_style = None; let mut fog_height = None; let mut fog_density = None; let mut fog_color = None; let mut global_weather = None; let mut sound_environment = None; let mut light_environment_tileset = None; let mut water_vertex_color = None; let mut script_mode = None; let mut graphics_mode = None; let mut game_data_version = None; let mut default_camera_zoom = None; let mut max_camera_zoom = None; let mut min_camera_zoom = None; ``` -------------------------------- ### unwrap_unchecked undefined behavior example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates that calling unwrap_unchecked on an Err is undefined behavior. The example is provided to illustrate the safety contract. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Parse and Snapshot a Map Source: https://docs.rs/war3parser/latest/src/war3parser/model/metadata.rs.html?search=std%3A%3Avec Demonstrates how to parse a map buffer from a file, resolve trigger strings, and generate a portable snapshot. ```rust use war3parser::prelude::War3MapMetadata; let buffer = std::fs::read("path/to/map.w3x")?; let mut metadata = War3MapMetadata::parse(&buffer)?; metadata.resolve_trigger_strings(); let snapshot = metadata.snapshot()?; ``` -------------------------------- ### Helper: w3i() builds a minimal v25 w3i buffer Source: https://docs.rs/war3parser/latest/src/war3parser/carve.rs.html?search= Constructs a minimal v25 w3i buffer with version, saves, editor version, four strings (name, author, and two empty strings), and 256 trailing zero bytes. Used to create test inputs for carve_deep. ```rust fn w3i(name: &str) -> Vec { let mut buf = Vec::new(); buf.extend(25u32.to_le_bytes()); buf.extend(0u32.to_le_bytes()); buf.extend(0u32.to_le_bytes()); for field in [name, "An Author", "", ""] { buf.extend(field.as_bytes()); buf.push(0); } buf.resize(buf.len() + 256, 0); buf } ``` -------------------------------- ### unwrap_err_unchecked safe example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates the safe usage of unwrap_err_unchecked on an Err value. The example asserts that the returned value matches the contained error. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### War3MapW3i Parsing Entry Points Source: https://docs.rs/war3parser/latest/src/war3parser/formats/w3i/mod.rs.html The primary entry points for parsing a complete war3map.w3i buffer or reader. ```rust impl War3MapW3i { /// Parse a complete `war3map.w3i` buffer. pub fn parse(data: &[u8]) -> Result { Self::parse_reader(&mut ByteReader::new(data)) } fn parse_reader(r: &mut ByteReader<'_>) -> Result { use FormatVersion as V; let version = V(r.u32()?); let v = version; let (saves, editor_version) = if v >= V::V18 { (Some(r.u32()?), Some(r.u32()?)) } else { (None, None) }; let build_version = (v >= V::V27).then(|| r.u32s()).transpose()?; let name = r.cstr_lossy()?; let author = r.cstr_lossy()?; let description = r.cstr_lossy()?; let recommended_players = r.cstr_lossy()?; let mut legacy_v8 = (v == V::V8) .then(|| -> Result { Ok(LegacyV8Fields { unk1: r.f32()?, unk2: r.i32()?, unk3: r.f32()?, unk4: r.f32()?, unk5: r.f32()?, unk6: r.i32()?, unk7: 0, }) }) .transpose()?; let camera_bounds = r.f32s()?; let camera_bounds_complements = (v >= V::V15).then(|| r.i32s()).transpose()?; let playable_size = r.i32s()?; if let Some(legacy) = legacy_v8.as_mut() { legacy.unk7 = r.i32()?; } let flags = r.u32()?; ``` -------------------------------- ### cloned() example for Result<&T, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the cloned method on Result<&T, E>. Clones the contents of the Ok part, converting a reference to a value. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### pub fn read_preview(&mut self) -> Result Source: https://docs.rs/war3parser/latest/war3parser/archive/struct.War3MapW3x.html?search= Decodes the preview image (war3mapPreview.tga / .blp). ```APIDOC ## read_preview ### Description Decodes the preview image (war3mapPreview.tga / .blp). ### Method read_preview ### Signature `pub fn read_preview(&mut self) -> Result` ### Returns - `Result` - The decoded preview image or an error. ``` -------------------------------- ### copied() example for Result<&T, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the copied method on Result<&T, E>. Copies the contents of the Ok part, converting a reference to a value. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Test: joins_a_string_table_split_across_sectors Source: https://docs.rs/war3parser/latest/src/war3parser/carve.rs.html?search= Builds an archive with a w3i sector and two string table sectors, where the first sector contains entry 1 and the second contains entry 900. Asserts both entries are present after carving. ```rust #[test] fn joins_a_string_table_split_across_sectors() { let mut archive = sector(&w3i("TRIGSTR_900")); archive.extend(sector(wts_entry(1, "first sector").as_bytes())); archive.extend(sector(wts_entry(900, "跨扇区的标题").as_bytes())); let carved = carve_deep(&archive).expect("w3i should be carved"); let strings = carved.strings.as_ref().expect("table should be carved"); assert_eq!(strings.get(1), Some("first sector")); assert_eq!(strings.get(900), Some("跨扇区的标题")); } ``` -------------------------------- ### unwrap_or_else example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates unwrap_or_else, which returns the contained Ok value or computes it from a closure. The example defines a count function and shows it being called on both Ok and Err values. ```rust fn count(x: &str) -> usize { x.len() } assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Rust: image module implementation Source: https://docs.rs/war3parser/latest/src/war3parser/model/image.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines War3Image and War3ImageData structs, with methods to load BLP/TGA buffers, fallback decoding, and conversion to a PNG data-URL. Uses base64 and image crates. ```rust 1//! Map images: in-memory raster + portable PNG data-URL form. use std::io::Write; use base64::{engine::general_purpose, write::EncoderWriter}; use image::{codecs::tga::TgaDecoder, DynamicImage, ImageOutputFormat}; use image_blp::{convert::blp_to_image, parser::load_blp_from_buf}; use crate::error::{Error, Result}; /// Raster image held in memory (not directly serializable). #[derive(Debug, Clone)] pub struct War3Image { pub data: DynamicImage, pub filename: String, } /// Portable image representation used by CLI dumps and WASM. #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone)] pub struct War3ImageData { /// `data:image/png;base64,...` pub data_url: String, pub width: u32, pub height: u32, pub filename: String, } impl War3Image { /// Decode a BLP buffer. pub fn load_blp(buffer: &[u8], filename: &str) -> Result { let blp = load_blp_from_buf(buffer)?; Ok(Self { data: blp_to_image(&blp, 0)?, filename: filename.to_string(), }) } /// Decode a TGA buffer. pub fn load_tga(buffer: &[u8], filename: &str) -> Result { let decoder = TgaDecoder::new(std::io::Cursor::new(buffer))?; Ok(Self { data: DynamicImage::from_decoder(decoder)?, filename: filename.to_string(), }) } /// Decode a buffer, trying BLP first, then TGA. pub fn from_buffer(data: &[u8], filename: &str) -> Result { Self::load_blp(data, filename) .or_else(|_| Self::load_tga(data, filename)) .map_err(|_| Error::UnsupportedImage(filename.to_string())) } /// Encode as a portable PNG data-URL snapshot. pub fn to_data(&self) -> Result { War3ImageData::try_from(self) } } impl TryFrom<&War3Image> for War3ImageData { type Error = Error; fn try_from(image: &War3Image) -> Result { let mut png = std::io::Cursor::new(Vec::new()); image.data.write_to(&mut png, ImageOutputFormat::Png)?; let mut encoder = EncoderWriter::new(Vec::new(), &general_purpose::STANDARD); encoder.write_all(&png.into_inner())?; let encoded = encoder.finish()?; let encoded = String::from_utf8(encoded).expect("base64 output is always ASCII"); Ok(Self { data_url: format!("data:image/png;base64,{encoded}"), width: image.data.width(), height: image.data.height(), filename: image.filename.clone(), }) } } ``` -------------------------------- ### cloned() example for Result<&mut T, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the cloned method on Result<&mut T, E>. Clones the contents of the Ok part, converting a mutable reference to a value. ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### copied() example for Result<&mut T, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the copied method on Result<&mut T, E>. Copies the contents of the Ok part, converting a mutable reference to a value. ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Test: prefers_the_richest_string_table Source: https://docs.rs/war3parser/latest/src/war3parser/carve.rs.html?search= Builds an archive with a w3i sector, noise, a sector containing 'STRING ' text, more noise, and a sector with two string entries. After resolving, the name becomes 'two', showing the richer table is preferred. ```rust #[test] fn prefers_the_richest_string_table() { let mut archive = sector(&w3i("TRIGSTR_002")); archive.extend(vec![0xAB; 16]); archive.extend(sector(b"call BJDebugMsg(\"STRING \")")); archive.extend(vec![0xAB; 16]); archive.extend(sector( format!("{}{}", wts_entry(1, "one"), wts_entry(2, "two")).as_bytes(), )); let mut carved = carve_deep(&archive).expect("w3i should be carved"); carved.resolve_trigger_strings(); assert_eq!(carved.info.name, "two"); } ``` -------------------------------- ### War3MapW3x::open Source: https://docs.rs/war3parser/latest/src/war3parser/archive.rs.html?search=std%3A%3Avec Loads a map from a file path. Reads the file into a buffer and delegates to from_vec. ```APIDOC ## War3MapW3x::open ### Description Loads a map from a file path. Reads the file into a buffer and delegates to from_vec. ### Method open ### Signature pub fn open(path: impl AsRef) -> Result ### Parameters - **path** (impl AsRef) - Required - The file path to the map. ### Returns - **Result** - The loaded map or an error. ``` -------------------------------- ### or_else chaining example Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Demonstrates using or_else to chain fallible operations for control flow. The example defines sq and err functions and shows how or_else applies the closure only when the result is Err. ```rust fn sq(x: u32) -> Result { Ok(x * x) } fn err(x: u32) -> Result { Err(x) } assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2)); assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2)); assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9)); assert_eq!(Err(3).or_else(err).or_else(err), Err(3)); ``` -------------------------------- ### as_ref: convert Result to Result of references Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Shows how `as_ref` converts a `Result` into a `Result` of references, leaving the original value in place. The example demonstrates both `Ok` and `Err` cases. ```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")); ``` -------------------------------- ### W3I carving tests and helpers Source: https://docs.rs/war3parser/latest/src/war3parser/carve.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Test helpers and unit tests for carving a W3I archive from surrounding noise. The sector helper zlib-compresses payloads with a 0x02 prefix, w3i builds a minimal v25 header with four strings, and wts_entry formats a trigger string entry. Tests cover carving a W3I from noise, resolving trigger strings from a carved table, joining a string table split across sectors, and rejecting payloads without a valid W3I. ```rust fn sector(payload: &[u8]) -> Vec { let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); encoder.write_all(payload).unwrap(); let mut out = vec![0x02]; out.extend(encoder.finish().unwrap()); out } ``` ```rust fn w3i(name: &str) -> Vec { let mut buf = Vec::new(); buf.extend(25u32.to_le_bytes()); buf.extend(0u32.to_le_bytes()); buf.extend(0u32.to_le_bytes()); for field in [name, "An Author", "", ""] { buf.extend(field.as_bytes()); buf.push(0); } buf.resize(buf.len() + 256, 0); buf } ``` ```rust fn wts_entry(id: u32, value: &str) -> String { format!("STRING {id}\n{{\n{value}\n}}\n") } ``` ```rust #[test] fn carves_a_w3i_out_of_surrounding_noise() { let mut archive = vec![0xAB; 4096]; archive.extend(sector(&w3i("守卫剑阁"))); archive.extend(vec![0xCD; 4096]); let carved = carve_deep(&archive).expect("w3i should be carved"); assert_eq!(carved.info.name, "守卫剑阁"); assert_eq!(carved.info.author, "An Author"); } ``` ```rust #[test] fn resolves_trigger_strings_from_a_carved_string_table() { let mut archive = sector(&w3i("TRIGSTR_001")); archive.extend(sector(b"STRING 1\n{\n\xe6\x94\xbb\xe5\xae\x88\n}\n")); let mut carved = carve_deep(&archive).expect("w3i should be carved"); assert_eq!(carved.info.name, "TRIGSTR_001"); carved.resolve_trigger_strings(); assert_eq!(carved.info.name, "攻守"); } ``` ```rust #[test] fn joins_a_string_table_split_across_sectors() { let mut archive = sector(&w3i("TRIGSTR_900")); archive.extend(sector(wts_entry(1, "first sector").as_bytes())); archive.extend(sector(wts_entry(900, "跨扇区的标题").as_bytes())); let carved = carve_deep(&archive).expect("w3i should be carved"); let strings = carved.strings.as_ref().expect("table should be carved"); assert_eq!(strings.get(1), Some("first sector")); assert_eq!(strings.get(900), Some("跨扇区的标题")); } ``` ```rust #[test] fn a_payload_with_no_w3i_yields_nothing() { let mut archive = vec![0xAB; 2048]; archive.extend(sector(b"not a w3i, just bytes")); assert!(carve_deep(&archive).is_none()); } ``` ```rust #[test] fn rejects_an_inflatable_sector_that_is_not_a_w3i() { let mut bogus = Vec::new(); bogus.extend(99u32.to_le_bytes()); // version outside the known ladder bogus.extend(b"\0\0\0\0"); bogus.resize(512, 0); assert!(carve_deep(§or(&bogus)).is_none()); } ``` -------------------------------- ### flatten() example for Result, E> Source: https://docs.rs/war3parser/latest/war3parser/error/type.Result.html?search=u32+-%3E+bool Example for the flatten method on Result, E>. Converts a nested Result into a single Result, removing one level of nesting. ```rust let x: Result, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` -------------------------------- ### Struct Import Source: https://docs.rs/war3parser/latest/war3parser/formats/imp/struct.Import.html?search=std%3A%3Avec Documentation for the Import struct, its fields, methods, and trait implementations. ```APIDOC ## Struct Import ### Description Represents one imported file entry in a Warcraft III map. ### Fields - **is_custom** (u8) - Flag byte: WC3MapSpec uses 8 = standard, 13 = custom path; older tools write 0/1 or 10. - **path** (String) - Path as stored in the file (standard imports omit the `war3mapimported\` prefix). ### Methods #### is_standard_path ```rust pub fn is_standard_path(&self) -> bool ``` Whether the stored path is implicitly under `war3mapimported\`. #### resolved_path ```rust pub fn resolved_path(&self) -> String ``` Full in-archive path (standard imports gain the `war3mapimported\` prefix). ### Trait Implementations - **Clone** - Provides `clone` and `clone_from` methods. - **Debug** - Provides `fmt` for formatting. - **Deserialize** - Provides `deserialize` for Serde deserialization. - **Serialize** - Provides `serialize` for Serde serialization. ```