### IdentFormat Search Examples Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormat.html?search= Provides examples of how to search for IdentFormat configurations. These examples demonstrate common search patterns. ```APIDOC ## IdentFormat Search Examples This section provides examples of how to search for IdentFormat configurations. ### Example Searches * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Install svd2rust Source: https://docs.rs/svd2rust/0.37.1/index.html Install the svd2rust command-line tool using Cargo. ```bash $ cargo install svd2rust ``` -------------------------------- ### HashMap keys Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Shows how to iterate over the keys of a HashMap. The order of iteration is not guaranteed. ```rust use std::collections::HashMap; let map: HashMap<&str, i32> = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut values: Vec<_> = map.keys().copied().collect(); values.sort(); assert_eq!(values, vec!["a", "b", "c"]); ``` -------------------------------- ### Example Interrupt Handler Usage Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search= Illustrates how to use the `interrupt!` macro to assign handlers for interrupts, including examples with and without local variables. ```rust interrupt!(TIM2, periodic); fn periodic() { print!("."); } interrupt!(TIM3, tick, locals: { tick: bool = false; }); fn tick(locals: &mut TIM3::Locals) { locals.tick = !locals.tick; if locals.tick { println!("Tick"); } else { println!("Tock"); } } ``` -------------------------------- ### HashMap len Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Shows how to get the number of elements currently stored in a HashMap. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### HashMap iter Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Shows how to iterate over key-value pairs in a HashMap. The order of iteration is not guaranteed. ```rust use std::collections::HashMap; let map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut count = 0; for (_key, _val) in map.iter() { count += 1; } assert_eq!(count, 3); ``` -------------------------------- ### HashMap Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html Demonstrates basic HashMap operations including insertion, removal of an entry, and attempting to remove a non-existent key. ```rust let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove_entry(&1), Some((1, "a"))); assert_eq!(map.remove(&1), None); ``` -------------------------------- ### HashMap capacity Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Demonstrates how to check the capacity of a HashMap. This is useful for pre-allocating memory when the approximate number of elements is known. ```rust use std::collections::HashMap; let map: HashMap = HashMap::with_capacity(100); assert!(map.capacity() >= 100); ``` -------------------------------- ### HashMap values Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Demonstrates iterating over the values of a HashMap. The order of iteration is not guaranteed. ```rust use std::collections::HashMap; let map: HashMap<&str, i32> = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); let mut values: Vec<_> = map.values().copied().collect(); values.sort(); assert_eq!(values, vec![1, 2, 3]); ``` -------------------------------- ### Example Searches in svd2rust Source: https://docs.rs/svd2rust/0.37.1/svd2rust/fn.generate.html?search= Demonstrates common search patterns that can be performed, such as searching for specific types or type transformations. ```rust std::vec ``` ```rust u32 -> bool ``` ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Register API Signatures (CR2 Example) Source: https://docs.rs/svd2rust/0.37.1/svd2rust?search=std%3A%3Avec Illustrates the signatures for the `modify`, `read`, and `write` methods available for a register like CR2. ```rust impl CR2 { /// Modifies the contents of the register pub fn modify(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { .. } /// Reads the contents of the register pub fn read(&self) -> R { .. } /// Writes to the register pub fn write(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { .. } } impl crate::ResetValue for CR2 { type Type = u32; fn reset_value() -> Self::Type { 0 } } ``` -------------------------------- ### Basic Search Example: std::vec Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Config.html?search= Demonstrates a basic search query for 'std::vec'. This is a common pattern for finding vector-related types or functions. ```rust std::vec ``` -------------------------------- ### MSP430 Device Crate Cargo.toml Configuration Source: https://docs.rs/svd2rust/0.37.1/index.html Example Cargo.toml for an MSP430 device crate, including essential dependencies and the 'rt' feature for runtime support. ```toml [dependencies] critical-section = { version = "1.0", optional = true } ``` ```toml msp430 = "0.4.0" ``` ```toml msp430-rt = { version = "0.4.0", optional = true } ``` ```toml vcell = "0.1.0" ``` ```toml [features] rt = ["msp430-rt/device"] ``` -------------------------------- ### Generate SVD Crate for MSP430 Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search=u32+-%3E+bool Example command to generate a Rust crate for an MSP430 microcontroller from its SVD file. This process involves using `svd2rust` and then organizing the output files. ```sh $ svd2rust -g --target=msp430 -i msp430g2553.svd $ rm -rf src $ form -i lib.rs -o src/ && rm lib.rs $ mv generic.rs src/ $ cargo fmt ``` -------------------------------- ### Accessing Peripherals Safely Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html Example of safely taking a peripheral instance and writing to a register. This method can only be called once. ```rust let mut peripherals = stm32f30x::Peripherals::take().unwrap(); peripherals.GPIOA.odr().write(|w| w.bits(1)); ``` -------------------------------- ### Example: Basic Interrupt Handler Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search=u32+-%3E+bool Illustrates the basic usage of the `interrupt!` macro to assign a function `periodic` as the handler for the `TIM2` interrupt. ```Rust interrupt!(TIM2, periodic); fn periodic() { print!("."); } ``` -------------------------------- ### Type Conversion Search Example: u32 to bool Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Config.html?search= Illustrates a search for type conversions from 'u32' to 'bool'. This pattern is useful for identifying functions or methods that perform such transformations. ```rust u32 -> bool ``` -------------------------------- ### RISC-V Device Crate Cargo.toml Configuration Source: https://docs.rs/svd2rust/0.37.1/index.html Example Cargo.toml for a RISC-V device crate, detailing dependencies and features like 'rt' and 'v-trap' for runtime and vectored trap support. ```toml [dependencies] critical-section = { version = "1.0", optional = true } ``` ```toml riscv = "0.12.1" ``` ```toml riscv-peripheral = "0.2.0" ``` ```toml riscv-rt = { version = "0.13.0", optional = true } ``` ```toml vcell = "0.1.0" ``` ```toml [features] rt = ["riscv-rt"] ``` ```toml v-trap = ["rt", "riscv-rt/v-trap"] ``` -------------------------------- ### Cargo.toml for Cortex-M Device Crate Source: https://docs.rs/svd2rust/0.37.1/index.html Example Cargo.toml configuration for a device crate targeting Cortex-M, including necessary dependencies and the 'rt' feature. ```toml [dependencies] critical-section = { version = "1.0", optional = true } cortex-m = "0.7.6" cortex-m-rt = { version = "0.6.13", optional = true } vcell = "0.1.2" [features] rt = ["cortex-m-rt/device"] ``` -------------------------------- ### HashMap is_empty Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Demonstrates checking if a HashMap contains any elements. Returns true if the map is empty, false otherwise. ```rust use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### Configuring GPIO Pins with svd2rust Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search= Example of configuring GPIO pins as inputs using svd2rust's peripheral proxy API. The peripheral proxy is destroyed after configuration, freezing the register settings. ```rust gpioa.moder.reset(); drop(gpioa); (PA0 { _0: () }, PA1 { _0: () }, ..) ``` -------------------------------- ### Example Usage of Interrupt Macro with Locals Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/generate/interrupt.rs.html?search= Demonstrates how to use the `interrupt!` macro to define an interrupt handler with local state. The `locals` block specifies variables and their initial values. ```rust interrupt!(TIM3, tick, locals: { tick: bool = false; }); fn tick(locals: &mut TIM3::Locals) { locals.tick = !locals.tick; if locals.tick { println!("Tick"); } else { println!("Tock"); } } ``` -------------------------------- ### Cortex-M Device Crate Cargo.toml Configuration Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html Example Cargo.toml configuration for a Cortex-M device crate, including optional features for runtime support and critical sections. ```toml [dependencies] critical-section = { version = "1.0", optional = true } cortex-m = "0.7.6" cortex-m-rt = { version = "0.6.13", optional = true } vcell = "0.1.2" [features] rt = ["cortex-m-rt/device"] ``` -------------------------------- ### Get Disjoint Unchecked Mut Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates retrieving mutable references to disjoint elements from a collection using `get_disjoint_unchecked_mut`. This is unsafe and requires ensuring keys do not overlap. ```rust let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Bodleian Library", ]) }) else { panic!() }; ``` ```rust let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Library of Congress", ]) }; assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); ``` ```rust let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "New York Public Library", ]) }; // Missing keys result in None assert_eq!(got, [Some(&mut 1807), None]); ``` -------------------------------- ### load_from Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html Loads and parses a [Device](svd::Device) from a string slice, applying the specified configuration and validation level. ```APIDOC ## load_from ### Description Load a [Device](svd::Device) from a string slice with given [config](crate::config::Config). ### Function Signature `pub fn load_from(input: &str, config: &Config) -> Result` ### Parameters - **input** (`&str`): A string slice containing the SVD content (XML or YAML). - **config** (`&Config`): A reference to the configuration object, including `source_type` and `strict` validation settings. ### Returns - `Result`: A `Result` containing the parsed `svd::Device` on success. Returns an error if parsing fails or validation fails at the specified level. ``` -------------------------------- ### Register Access Methods (read, modify, write) Source: https://docs.rs/svd2rust/0.37.1/svd2rust/index.html Each register exposes `read`, `modify`, and `write` methods depending on its access permissions (read-only, write-only, read-write). Signatures for these methods are shown using the `CR2` register as an example. ```APIDOC ## Register Access Methods Each register in the register block exposes a combination of the `read`, `modify`, and `write` methods. The available methods depend on whether the register is read-only, read-write, or write-only. ### Signatures ```rust impl CR2 { /// Modifies the contents of the register pub fn modify(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { // ... implementation details ... } /// Reads the contents of the register pub fn read(&self) -> R { /* ... */ } /// Writes to the register pub fn write(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { // ... implementation details ... } } ``` ``` -------------------------------- ### Customizing Identifier Formatting with --ident-format Source: https://docs.rs/svd2rust/0.37.1/svd2rust/index.html?search=u32+-%3E+bool Provides an example of how to use the `--ident-format` flag to customize the naming conventions for generated Rust identifiers, such as fields, enums, and peripherals. This example shows reverting to the legacy behavior for `field_reader`. ```rust # To revert old behavior for `field_reader` you need to pass flag `-f field_reader::c:_R`. # Also you can do the same in config file: # ``` # [ident_formats.field_reader] # case = constant # suffix = "_R" # ``` # To revert old behavior for all identifiers you may pass `--ident-formats-theme legacy`. ``` -------------------------------- ### type_id Implementation for Generic Type T Source: https://docs.rs/svd2rust/0.37.1/svd2rust/generate/register/enum.RWEnum.html?search=std%3A%3Avec Gets the TypeId of a type that implements the 'static trait. ```rust fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more Source ``` -------------------------------- ### load_from Function Signature Source: https://docs.rs/svd2rust/0.37.1/svd2rust/fn.load_from.html Loads a Device from a string slice with the provided configuration. ```APIDOC ## load_from ### Description Load a Device from a string slice with given config. ### Signature ```rust pub fn load_from(input: &str, config: &Config) -> Result ``` ### Parameters * `input`: A string slice representing the input SVD data. * `config`: A reference to the `Config` struct containing configuration options. ### Returns A `Result` which is either `Ok(Device)` on success or an error if loading fails. ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/enum.Case.html?search= Implements the Any trait for generic types T, providing a `type_id` method to get the TypeId of the instance. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### HashMap values_mut Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Illustrates how to iterate over mutable references to the values in a HashMap, allowing in-place modification. ```rust use std::collections::HashMap; let mut map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); for val in map.values_mut() { *val += 10; } assert_eq!(map.get("a"), Some(&11)); assert_eq!(map.get("b"), Some(&12)); assert_eq!(map.get("c"), Some(&13)); ``` -------------------------------- ### Settings Implementations Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Settings.html?search=u32+-%3E+bool Provides methods for interacting with the Settings struct, including updating settings from a source and generating extra build configurations. ```APIDOC ## Implementations for Settings ### `update_from(&mut self, source: Self)` Updates the settings from a given source `Settings` struct. ### `extra_build(&self) -> Option` Generates an `Option` for extra build configurations based on the current settings. ``` -------------------------------- ### get Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Returns a reference to the value corresponding to the key. The key can be any borrowed form of the map’s key type. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but `Hash` and `Eq` on the borrowed form must match those for the key type. ### Method `get` ### Parameters #### Path Parameters - **k** (&Q) - Required - The key to look up. #### Return Value - `Option<&V>` - An `Option` containing a reference to the value if the key exists, otherwise `None`. ``` -------------------------------- ### RiscvConfig extra_build Method Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvConfig.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Generates additional build configurations based on the RiscvConfig. ```APIDOC ## impl RiscvConfig ### pub fn extra_build(&self) -> Option Generates additional build configurations based on the RiscvConfig. ``` -------------------------------- ### Error::cause Implementation for SvdError (Deprecated) Source: https://docs.rs/svd2rust/0.37.1/svd2rust/enum.SvdError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Deprecated method for getting the cause of the error. Replaced by Error::source. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Region Size Method Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/generate/peripheral.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a method to calculate the total size of a `Region` based on its start and end offsets. ```rust fn size(&self) -> u32 { self.end - self.offset } ``` -------------------------------- ### Settings Implementations Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Settings.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods for updating and generating build tokens from `Settings`. It also includes standard trait implementations like Clone, Debug, Default, Deserialize, and PartialEq. ```APIDOC ## Implementations ### impl Settings * `pub fn update_from(&mut self, source: Self)`: Updates the settings from another `Settings` instance. * `pub fn extra_build(&self) -> Option`: Returns an optional `TokenStream` for extra build configurations. ``` ```APIDOC ### impl Clone for Settings * `fn clone(&self) -> Settings`: Returns a duplicate of the value. * `fn clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. ``` ```APIDOC ### impl Debug for Settings * `fn fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. ``` ```APIDOC ### impl Default for Settings * `fn default() -> Settings`: Returns the default value for the type. ``` ```APIDOC ### impl<'de> Deserialize<'de> for Settings * `fn deserialize<__D>(__deserializer: __D) -> Result`: Deserializes this value from the given Serde deserializer. ``` ```APIDOC ### impl PartialEq for Settings * `fn eq(&self, other: &Settings) -> bool`: Tests for equality between two `Settings` instances. * `fn ne(&self, other: &Rhs) -> bool`: Tests for inequality. ``` ```APIDOC ### impl Eq for Settings ``` ```APIDOC ### impl StructuralPartialEq for Settings ``` -------------------------------- ### Get full name of a peripheral Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/util.rs.html?search=u32+-%3E+bool Returns the name of the peripheral. The `ignore_group` parameter is present for consistency with `RegisterInfo` but is not used for peripherals. ```rust impl FullName for PeripheralInfo { fn fullname(&self, _ignore_group: bool) -> Cow<'_, str> { self.name.as_str().into() } } ``` -------------------------------- ### docs.rs Metadata Configuration Source: https://docs.rs/svd2rust/0.37.1/index.html Recommended configuration block for Cargo.toml to enable all features and use specific rustdoc arguments when hosting library documentation on docs.rs. ```toml [package.metadata.docs.rs] all-features = true rustdoc-args = ["--generate-link-to-definition"] ``` -------------------------------- ### Generate Documentation Command Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html Command to generate documentation for the generated library, including enabling all features and opening the documentation. ```sh RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options" cargo +nightly doc --all-features --open ``` -------------------------------- ### Demonstrate Single Peripheral Instance Access Source: https://docs.rs/svd2rust/0.37.1/index.html Illustrates that `Peripherals::take` can only be successfully called once, returning `Some` the first time and `None` on subsequent calls. ```rust let ok = stm32f30x::Peripherals::take().unwrap(); let panics = stm32f30x::Peripherals::take().unwrap(); ``` -------------------------------- ### HashMap iter_mut Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Demonstrates iterating over key-value pairs with mutable references to the values, enabling modification of values during iteration. ```rust use std::collections::HashMap; let mut map = HashMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } assert_eq!(map.get("a"), Some(&2)); assert_eq!(map.get("b"), Some(&4)); assert_eq!(map.get("c"), Some(&6)); ``` -------------------------------- ### PartialEq Implementation for RiscvPlicConfig Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvPlicConfig.html?search=u32+-%3E+bool Provides equality comparison for RiscvPlicConfig instances. ```APIDOC ### impl PartialEq for RiscvPlicConfig #### fn eq(&self, other: &RiscvPlicConfig) -> bool Tests for `self` and `other` values to be equal, and is used by `==`. ``` ```APIDOC #### fn ne(&self, other: &Rhs) -> bool Tests for `!=`. ``` -------------------------------- ### RiscvConfig::extra_build Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvConfig.html?search=u32+-%3E+bool An implementation method for RiscvConfig that returns an Option, likely used for build-related operations. ```APIDOC ## impl RiscvConfig ### pub fn extra_build(&self) -> Option This method is part of the RiscvConfig implementation and returns an `Option`. ``` -------------------------------- ### Getting a reference to the HashMap's BuildHasher Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Use hasher to obtain a reference to the map's BuildHasher, which is used for hashing keys. ```rust use std::collections::HashMap; use std::hash::RandomState; let hasher = RandomState::new(); let map: HashMap = HashMap::with_hasher(hasher); let hasher: &RandomState = map.hasher(); ``` -------------------------------- ### RiscvEnumItem PartialEq Implementation Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvEnumItem.html?search= Enables equality comparison for RiscvEnumItem instances. ```APIDOC ## Trait Implementation: PartialEq ### Method: eq `fn eq(&self, other: &RiscvEnumItem) -> bool` ### Description Tests if two `RiscvEnumItem` instances are equal. ### Method: ne `fn ne(&self, other: &Rhs) -> bool` ### Description Tests if two `RiscvEnumItem` instances are not equal. ``` -------------------------------- ### Modifying a Register by Setting a Bit Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search= Sets the START bit of the CR2 register to 1 while preserving the state of other bits. This is an unsafe operation. ```rust i2c1.cr2().modify(|_, w| unsafe { w.start().bit(true) }); ``` -------------------------------- ### PartialEq Implementation for Settings Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Settings.html Provides the `eq` method for testing equality between two `Settings` values. ```rust fn eq(&self, other: &Settings) -> bool ``` -------------------------------- ### Register Access Methods Signatures Source: https://docs.rs/svd2rust/0.37.1/svd2rust/index.html Signatures for the `modify`, `read`, and `write` methods available for registers, demonstrating their usage with a CR2 register example. ```rust impl CR2 { /// Modifies the contents of the register pub fn modify(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { .. } /// Reads the contents of the register pub fn read(&self) -> R { .. } /// Writes to the register pub fn write(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { .. } } implement crate::ResetValue for CR2 { type Type = u32; fn reset_value() -> Self::Type { 0 } } ``` -------------------------------- ### HashMap drain Method Example Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Illustrates clearing a HashMap and consuming its elements as an iterator. This method retains the allocated memory for potential reuse. ```rust use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.insert(2, "b"); for (k, v) in a.drain().take(1) { assert!(k == 1 || k == 2); assert!(v == "a" || v == "b"); } assert!(a.is_empty()); ``` -------------------------------- ### Clone Implementation for RiscvClintConfig Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvClintConfig.html Provides methods for cloning RiscvClintConfig instances. Includes `clone` for creating a duplicate and `clone_from` for copy-assignment. ```rust fn clone(&self) -> RiscvClintConfig ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Loading SVD Device from String Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search= Loads a `svd::Device` from a string slice, applying validation based on the configuration's strictness. ```rust /// Load a [Device](svd::Device) from a string slice with given [config](crate::config::Config). pub fn load_from(input: &str, config: &Config) -> Result { use config::SourceType; use svd_parser::ValidateLevel; let validate_level = if config.strict { ValidateLevel::Strict } else { ValidateLevel::Weak }; let mut device = match config.source_type { SourceType::Xml => { let mut parser_config = svd_parser::Config::default(); parser_config.validate_level = validate_level; svd_parser::parse_with_config(input, &parser_config) .with_context(|| "Error parsing SVD XML file".to_string())? } #[cfg(feature = "yaml")] SourceType::Yaml => { let device: svd::Device = serde_yaml::from_str(input) .with_context(|| "Error parsing SVD YAML file".to_string())?; device.validate_all(validate_level)?; device } #[cfg(feature = "json")] ``` -------------------------------- ### Error::description Implementation for SvdError (Deprecated) Source: https://docs.rs/svd2rust/0.37.1/svd2rust/enum.SvdError.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Deprecated method for getting a string description of the error. Use the Display implementation or to_string() instead. ```rust fn description(&self) -> &str ``` -------------------------------- ### Writing to Registers Source: https://docs.rs/svd2rust/0.37.1/svd2rust/index.html The `write` method uses a `W` struct to construct valid states for a register. This example demonstrates modifying specific bits before writing. ```rust impl W { /// Bits 1:7 - Slave address bit 7:1 (master mode) pub fn sadd1(&mut self) -> SADD1_W { .. } /// Bit 0 - Slave address bit 0 (master mode) pub fn sadd0(&mut self) -> SADD0_W { .. } } ``` ```rust // Starting from the reset value, `0x0000_0000`, change the bitfields SADD0 // and SADD1 to `1` and `0b0011110` respectively and write that to the // register CR2. i2c1.cr2().write(|w| unsafe { w.sadd0().bit(true).sadd1().bits(0b0011110) }); // NOTE ^ unsafe because you could be writing a reserved bit pattern into // the register. In this case, the SVD doesn't provide enough information to // check whether that's the case. // NOTE The argument to `bits` will be *masked* before writing it to the // bitfield. This makes it impossible to write, for example, `6` to a 2-bit // field; instead, `6 & 3` (i.e. `2`) will be written to the bitfield. ``` -------------------------------- ### Default Implementation for Settings Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Settings.html Provides the `default` method for creating a default `Settings` value. ```rust fn default() -> Settings ``` -------------------------------- ### Generate Documentation with RUSTDOCFLAGS Source: https://docs.rs/svd2rust/0.37.1/index.html Command to generate documentation for the generated library, including specific RUSTDOCFLAGS for enhanced features like linking to definitions and unstable options. ```bash RUSTDOCFLAGS="--cfg docsrs --generate-link-to-definition -Z unstable-options" cargo +nightly doc --all-features --open ``` -------------------------------- ### Register Block Structure in svd2rust Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search= Defines the structure of a peripheral's register block, where each field represents a register. This example shows the RegisterBlock for I2C1. ```rust pub mod i2c1 { /// Register block #[repr(C)] pub struct RegisterBlock { cr1: CR1, cr2: CR2, oar1: OAR1, oar2: OAR2, dr: DR, } impl RegisterBlock { /// 0x00 - Control register 1 #[inline(always)] pub const fn cr1(&self) -> &CR1 { &self.cr1 } /// 0x04 - Control register 2 #[inline(always)] pub const fn cr2(&self) -> &CR2 { &self.cr2 } /// 0x08 - Own address register 1 #[inline(always)] pub const fn oar1(&self) -> &OAR1 { &self.oar1 } #[doc = "0x0c - Own address register 2"] #[inline(always)] pub const fn oar2(&self) -> &OAR2 { &self.oar2 } #[doc = "0x10 - Data register"] #[inline(always)] pub const fn dr(&self) -> &DR { &self.dr } } } ``` -------------------------------- ### Configuring Identifier Formats via Configuration File Source: https://docs.rs/svd2rust/0.37.1/svd2rust?search= Demonstrates how to customize identifier formatting (e.g., for field readers) using a configuration file, allowing for persistent changes to how svd2rust generates Rust identifiers. ```toml [ ident_formats.field_reader] case = "constant" suffix = "_R" ``` -------------------------------- ### get_disjoint_mut Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search=u32+-%3E+bool Attempts to get mutable references to multiple values in the map at once. Returns an array of results, with `None` for missing keys. Panics if keys overlap. ```APIDOC ## pub fn get_disjoint_mut( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N] ### Description Attempts to get mutable references to `N` values in the map at once. Returns an array of length `N` with the results of each query. For soundness, at most one mutable reference will be returned to any value. `None` will be used if the key is missing. This method performs a check to ensure there are no duplicate keys, which currently has a time-complexity of O(n^2), so be careful when passing many keys. ### Method `get_disjoint_mut` ### Parameters - **ks** ([&Q; N]) - An array of keys to look up. ### Returns An array of `Option<&mut V>` containing mutable references to the values if the keys are found and unique, otherwise `None`. ### Panics Panics if any keys are overlapping. ### Examples ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); // Get Athenæum and Bodleian Library let [Some(a), Some(b)] = libraries.get_disjoint_mut([ "Athenæum", "Bodleian Library", ]) else { panic!() }; // Assert values of Athenæum and Library of Congress let got = libraries.get_disjoint_mut([ "Athenæum", "Library of Congress", ]); assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); // Missing keys result in None let got = libraries.get_disjoint_mut([ "Athenæum", "New York Public Library", ]); assert_eq!( got, [ Some(&mut 1807), None ] ); ``` ```rust use std::collections::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_disjoint_mut([ "Athenæum", "Athenæum", ]); ``` ``` -------------------------------- ### Docs.rs Metadata Configuration Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html Recommended Cargo.toml metadata for hosting library documentation on docs.rs. ```toml [package.metadata.docs.rs] all-features = true rustdoc-args = ["--generate-link-to-definition"] ``` -------------------------------- ### Get mutable references to disjoint entries Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search=std%3A%3Avec Safely retrieves mutable references to values associated with distinct keys. Panics if keys overlap or are not found. ```rust // SAFETY: The keys do not overlap. let [Some(a), Some(b)] = (unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Bodleian Library", ]) }) else { panic!() }; ``` ```rust // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "Library of Congress", ]) }; assert_eq!( got, [ Some(&mut 1807), Some(&mut 1800), ], ); ``` ```rust // SAFETY: The keys do not overlap. let got = unsafe { libraries.get_disjoint_unchecked_mut([ "Athenæum", "New York Public Library", ]) }; // Missing keys result in None assert_eq!(got, [Some(&mut 1807), None]); ``` -------------------------------- ### Render Cluster Block Documentation Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/generate/peripheral.rs.html?search=std%3A%3Avec Generates the documentation string for a cluster block. It takes the cluster's description or name, resizes it, and escapes special characters for proper display. ```Rust /// Render a Cluster Block into `TokenStream` fn cluster_block( c: &mut Cluster, path: &BlockPath, dpath: Option, index: &Index, config: &Config, ) -> Result { let doc = c.description.as_ref().unwrap_or(&c.name); let doc = util::respace(doc); let doc = util::escape_special_chars(&doc); ``` -------------------------------- ### get Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns a reference to the value corresponding to the key. The key can be any borrowed form of the map’s key type, provided it implements `Hash` and `Eq`. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. ### Method `get` ### Parameters #### Path Parameters - **k** (&Q) - Required - The key to look up. Can be a borrowed form of the map's key type. ### Returns An `Option<&V>` containing a reference to the value if the key exists, otherwise `None`. ``` -------------------------------- ### PartialEq Implementation for RiscvClintConfig Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvClintConfig.html Enables comparison of RiscvClintConfig instances for equality using `eq` and inequality using `ne`. ```rust fn eq(&self, other: &RiscvClintConfig) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### entry Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.IdentFormats.html?search= Gets the given key’s corresponding entry in the map for in-place manipulation. This allows for modifying existing entries or inserting new ones. ```APIDOC ## pub fn entry(&mut self, key: K) -> Entry<'_, K, V, A> ### Description Gets the given key’s corresponding entry in the map for in-place manipulation. ### Method `entry` ### Parameters #### Path Parameters - **key** (K) - Required - The key to look up or insert. #### Return Value - `Entry<'_, K, V, A>` - An `Entry` enum that represents a vacant or occupied location in the map. ``` -------------------------------- ### Get Full Name of MaybeArray Element Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/util.rs.html Retrieves the full name of an element within a `MaybeArray` structure, removing dimension information if it's an array. ```rust pub fn name_of(maybe_array: &MaybeArray, ignore_group: bool) -> String { let fullname = maybe_array.fullname(ignore_group); if maybe_array.is_array() { fullname.remove_dim().into() } else { fullname.into() } } ``` -------------------------------- ### Config::extra_build Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/struct.Config.html?search=std%3A%3Avec Returns an `Option` which can be used for extra build configurations. ```APIDOC ## pub fn extra_build(&self) -> Option ### Description Returns an `Option` representing extra build configurations. ### Signature `pub fn extra_build(&self) -> Option` ``` -------------------------------- ### Sanitize Identifier with Prefix, Suffix, and Case Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/util.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Applies identifier formatting, ensures the name does not start with a digit by prepending an underscore if necessary, and sanitizes keywords. ```Rust impl IdentFormat { pub fn sanitize<'a>(&self, name: &'a str) -> Cow<'a, str> { let s = self.apply(name); let s = if s.as_bytes().first().unwrap_or(&0).is_ascii_digit() { Cow::from(format!("_{}", s)) } else { s }; match self.case { Some(Case::Snake) | None => sanitize_keyword(s), _ => s, } } } ``` -------------------------------- ### Generate MSP430 Device Crate Files Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Generate SVD file for MSP430 and then process it to create device crate files. This includes XML formatting. ```text $ msp430gen msp430g2553 > msp430g2553.svd $ xmllint -format msp430g2553.svd --output msp430g2553.svd ``` -------------------------------- ### RISC-V Interrupt Handler Setup Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/generate/riscv.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a core interrupt handler for the PLIC, enabling the dispatch of external interrupts. This requires the `rt` feature to be enabled. ```rust #[cfg(feature = "rt")] #[riscv_rt::core_interrupt(CoreInterrupt::#core_interrupt)] unsafe fn plic_handler() { let plic = unsafe { crate::#name::steal() }; let claim = plic.#ctx.claim(); if let Some(s) = claim.claim::() { unsafe { _dispatch_external_interrupt(s.number()) } claim.complete(s); } } ``` -------------------------------- ### Generate MSP430 Device Crate Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/lib.rs.html?search=u32+-%3E+bool Generate an SVD file for MSP430 using `msp430gen` and format it using `xmllint`. ```bash $ msp430gen msp430g2553 > msp430g2553.svd $ xmllint -format msp430g2553.svd --output msp430g2553.svd ``` -------------------------------- ### Default Implementation for RiscvClintConfig Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvClintConfig.html Provides a `default` method to create a RiscvClintConfig instance with its default values. ```rust fn default() -> RiscvClintConfig ``` -------------------------------- ### Get Peripheral Instance and Write to Register Source: https://docs.rs/svd2rust/0.37.1/index.html Obtain a peripheral instance using `Peripherals::take` and write a value to one of its registers. This requires the `critical-section` feature. ```rust let mut peripherals = stm32f30x::Peripherals::take().unwrap(); peripherals.GPIOA.odr().write(|w| w.bits(1)); ``` -------------------------------- ### RiscvEnumItem StructuralPartialEq Implementation Source: https://docs.rs/svd2rust/0.37.1/svd2rust/config/riscv/struct.RiscvEnumItem.html?search= Enables structural partial equality comparison for RiscvEnumItem instances. ```APIDOC ## Trait Implementation: StructuralPartialEq This trait enables structural partial equality comparison for `RiscvEnumItem` instances. ``` -------------------------------- ### Legacy Theme Identifier Formats Source: https://docs.rs/svd2rust/0.37.1/src/svd2rust/config.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the legacy theme for identifier formats, starting with common formats and then applying ConstantCase with specific suffixes for readers and writers. ```rust pub fn legacy_theme() -> Self { let mut map = Self::common(); let constant = IdentFormat::default().constant_case(); map.extend([ ("field_reader".into(), constant.clone().suffix("_R")), ("field_writer".into(), constant.clone().suffix("_W")), ]); map } ```