### Display output example Source: https://docs.rs/z80emu/latest/z80emu/struct.CpuDebug.html Example output of the Display formatting for CpuDebug. ```text 143 SUB B [144] 144 ADC HL, HL [237, 106] 146 JR NC, 151 [48, 3] ``` -------------------------------- ### Example for as_ref method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the as_ref method, which converts Result to Result with references. ```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")); ``` -------------------------------- ### into_ok example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use into_ok on a Result that is guaranteed to be Ok, converting it to the contained value. ```rust let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Example for map method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the map method, which applies a function to the Ok value. ```rust let line = "1\n2\n3\n4\n"; for num in line.lines() { match num.parse::().map(|i| i * 2) { Ok(n) => println!("{n}"), Err(..) => {} } } ``` -------------------------------- ### CpuDebugFn usage example Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Shows how to pass a debug function to the execute_instruction method. The example is marked as ignore in the source, indicating it is not compiled. ```rust cpu.execute_instruction::<_,_,CpuDebugFn>(control, clock, None, code) ``` -------------------------------- ### Example for ok method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the ok method, which converts Result to Option, discarding the error. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Example for is_ok method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the is_ok method, which returns true if the result is Ok. ```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); ``` -------------------------------- ### expect recommended message style example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows the recommended style for expect messages, describing why the Result should be Ok. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### iter example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::iter to get an iterator over the contained value, yielding one value if Ok and none if Err. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### unwrap panic example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates that unwrap panics with the Err content when the Result is Err. ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Example for is_ok_and method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the is_ok_and method, which checks if the result is Ok and the value matches a predicate. ```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); ``` -------------------------------- ### Example for as_mut method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the as_mut method, which converts Result to Result with mutable references. ```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); ``` -------------------------------- ### unwrap basic usage example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows that unwrap returns the contained Ok value. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### Memory Trait Implementation Example Source: https://docs.rs/z80emu/latest/src/z80emu/macros.rs.html Example usage of the forwarding macros within a test module to implement the Memory trait for nested bus structures. ```rust impl<'a, B: crate::Memory> crate::Memory for NBus<'a, B> { forward_host_memory_types!{ @ => RBus<'a, B> } forward_host_memory_methods!{ @ref => |m| m.bus_ref() } forward_host_memory_methods!{ @mut => |m| m.bus_mut() } } impl crate::Memory for RBus<'_, B> { forward_host_memory_types!{ @ => B } forward_host_memory_methods!{ @ref => |m| m.bus_ref() } forward_host_memory_methods!{ @mut => |m| m.bus_mut() } } ``` -------------------------------- ### Custom formatting output example Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Shows the output of the custom format string, with uppercase hex for byte codes. ```text 008f : SUB B [90] 0090 : ADC HL, HL [ED, 6A] 0092 : JR NC, 0x0097 [30, 03] ``` -------------------------------- ### or example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the or method, which returns the second Result if the first is Err, otherwise returns the first Ok. Arguments are eagerly evaluated. ```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)); ``` -------------------------------- ### into_ok example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows usage of into_ok on a Result with an infallible error type (!), returning the Ok value without panicking. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } ``` -------------------------------- ### expect panic example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates that expect panics with the provided message and the Err content when the Result is Err. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` -------------------------------- ### ArrayVec::new example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Creates a new empty ArrayVec with a specified capacity and demonstrates pushing elements and checking capacity. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::<_, 16>::new(); array.push(1); array.push(2); assert_eq!(&array[..], &[1, 2]); assert_eq!(array.capacity(), 16); ``` -------------------------------- ### Implement custom wrapper with selective forwarding Source: https://docs.rs/z80emu/latest/src/z80emu/macros.rs.html This example shows how to wrap a bus to add custom behavior while selectively forwarding types and methods. It also demonstrates splitting memory methods between those requiring immutable and mutable access. ```rust use core::num::NonZeroU16; use z80emu::*; struct DebugBus<'a, B> { bus: &'a mut B, irq_data: Option } // To illustrate an example with accessors: impl<'a, B> DebugBus<'a, B> { fn bus_mut(&mut self) -> &mut B { &mut *self.bus } fn bus_ref(&self) -> &B { &*self.bus } } impl Io for DebugBus<'_, B> { // while we should use just this: // forward_host_io_types!{ @ => B } // here we illustrate how to forward only selected types: type Timestamp = ::Timestamp; forward_host_io_types! { (WrIoBreak RetiBreak) => B } /// Capture data from an interrupting device. fn irq_data(&mut self, pc: u16, ts: Self::Timestamp) -> (u8, Option) { let (data, delay) = self.bus.irq_data(pc, ts); self.irq_data = Some(data); (data, delay) } // forward remaining methods forward_host_io_methods! { (write_io, read_io, is_irq, reti) => |me| me.bus_mut() } // be carefull if you don't forward a method, a default implementation // will be used for that method instead } impl Memory for DebugBus<'_, B> { forward_host_memory_types!{ @ => B } // here we can split implementations between methods that access &self: forward_host_memory_methods!{ @ref => |me| me.bus_ref() } // from methods accessing &mut self forward_host_memory_methods!{ @mut => |me| me.bus_mut() } } ``` -------------------------------- ### and example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the and method, which returns the second Result if the first is Ok, otherwise returns the first Err. Note that arguments are eagerly evaluated. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### Example for is_err method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the is_err method, which returns true 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_or_default example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how unwrap_or_default returns the Ok value or a default (0 for integers) when parsing fails. ```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); ``` -------------------------------- ### Implement Z80 Fibonacci calculation Source: https://docs.rs/z80emu/latest/index.html This example demonstrates setting up a custom memory bus, initializing the Z80NMOS CPU, and executing a Fibonacci sequence program. It uses a T-state counter to track execution time and asserts the final register value. ```rust use z80emu::*; use opconsts::HALT_OPCODE; // Let's use the simple T-state counter. type TsClock = host::TsCounter; // Let's add some memory. #[derive(Clone, Debug, Default)] struct Bus { rom: [u8;11] } impl Io for Bus { type Timestamp = i32; type WrIoBreak = (); type RetiBreak = (); } impl Memory for Bus { type Timestamp = i32; fn read_debug(&self, addr: u16) -> u8 { self.rom[addr as usize] } } const FIB_N: u8 = 24; // 1..=24 let mut tsc = TsClock::default(); let mut fibbo = Bus { rom: [ 0x21, 0x00, 0x00, // 0x0000 LD HL, 0x0000 0x11, 0x01, 0x00, // 0x0003 LD DE, 0x0001 0xEB, // 0x0006 EX DE, HL 0x19, // 0x0007 ADD HL, DE 0x10, 0xFC, // 0x0008 DJNZ 0x0006 HALT_OPCODE // 0x000A HALT ] }; let mut cpu = Z80NMOS::default(); cpu.reset(); // PC = 0 cpu.set_reg(Reg8::B, None, FIB_N); // Cpu register B = FIB_N // Let's calculate a Fibbonacci number loop { match cpu.execute_next(&mut fibbo, &mut tsc, Some(|deb| println!("{:#X}", deb) )) { Err(BreakCause::Halt) => { break } _ => {} } } // the content of the HL registers let result = cpu.get_reg16(StkReg16::HL); assert_eq!(result, 46368); // Fib(24) // the number of T-states passed assert_eq!(tsc.as_timestamp(), 10+10+(FIB_N as i32)*(4+11+13)-5+4); ``` -------------------------------- ### inspect example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::inspect to call a function with a reference to the Ok value, returning the original result. ```rust let x: u8 = "4" .parse::() .inspect(|x| println!("original: {x}")) .map(|x| x.pow(3)) .expect("literal `4` should parse as a `u8`"); ``` -------------------------------- ### unwrap_or_else example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use unwrap_or_else to compute a default value from a closure when the Result is Err. ```rust fn count(x: &str) -> usize { x.len() } ``` -------------------------------- ### and_then example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use and_then to chain fallible operations. The closure is only called if the Result is Ok. ```rust fn sq_then_to_string(x: u32) -> Result { x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed") } 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")); ``` -------------------------------- ### into_err example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use into_err on a Result that is guaranteed to be Err, converting it to the contained error value. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### unwrap_or example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates unwrap_or, which returns the contained Ok value or a provided default. The default 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); ``` -------------------------------- ### Product example: multiply parsed numbers from vector of strings Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use the Product trait on Result to multiply parsed numbers from a vector of strings. If any string fails to parse, the operation returns an Err. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### as_deref_mut example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::as_deref_mut to convert a &mut Result to Result<&mut T::Target, &mut E> by dereferencing the Ok value mutably. ```rust let mut s = "HELLO".to_string(); let mut x: Result = Ok("hello".to_string()); let y: Result<&mut str, &mut u32> = Ok(&mut s); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); let mut i = 42; let mut x: Result = Err(42); let y: Result<&mut str, &mut u32> = Err(&mut i); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); ``` -------------------------------- ### and_then with std::io example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates chaining metadata() and modified() with and_then to handle potential I/O errors. ```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); ``` -------------------------------- ### Example for is_err_and method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the is_err_and method, which checks if the result is Err and the error matches a predicate. ```rust use std::io::{Error, ErrorKind}; let x: Result = Err(Error::new(ErrorKind::NotFound, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), true); let x: Result = Err(Error::new(ErrorKind::PermissionDenied, "!")); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Ok(123); assert_eq!(x.is_err_and(|x| x.kind() == ErrorKind::NotFound), false); let x: Result = Err("ownership".to_string()); assert_eq!(x.as_ref().is_err_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Example for err method Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates the err method, which converts Result to Option, discarding the success value. ```rust let x: Result = Ok(2); assert_eq!(x.err(), None); let x: Result = Err("Nothing here"); assert_eq!(x.err(), Some("Nothing here")); ``` -------------------------------- ### Implement traits using forwarding macros Source: https://docs.rs/z80emu/latest/src/z80emu/macros.rs.html This example demonstrates how to use the forwarding macros to implement Clock, Io, and Memory for wrapper types by delegating to an inner field. ```rust use z80emu::{*, host::TsCounter}; struct Ticks(TsCounter); struct BusWrap(B); impl Clock for Ticks { forward_host_clock_types!{ @ => TsCounter } forward_host_clock_methods!{ @ => |c| c.0 } } impl Io for BusWrap { forward_host_io_types!{ @ => B } forward_host_io_methods!{ @ => |b| b.0 } } impl Memory for BusWrap { forward_host_memory_types!{ @ => B } forward_host_memory_methods!{ @ => |b| b.0 } } ``` -------------------------------- ### expect_err panic example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates that expect_err panics with the provided message and the Ok content when the Result is Ok. ```rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### as_deref example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::as_deref to convert a Result to Result<&T::Target, &E> by dereferencing the Ok value. ```rust let x: Result = Ok("hello".to_string()); let y: Result<&str, &u32> = Ok("hello"); assert_eq!(x.as_deref(), y); let x: Result = Err(42); let y: Result<&str, &u32> = Err(&42); assert_eq!(x.as_deref(), y); ``` -------------------------------- ### iter_mut example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use iter_mut to mutate the contained value if Ok, and returns None for Err. ```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); ``` -------------------------------- ### map_or_default example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::map_or_default to apply a function to the Ok value or return the default value for the type U when Err. ```rust let x: Result<_, &str> = Ok("foo"); let y: Result<&str, _> = Err("bar"); assert_eq!(x.map_or_default(|x| x.len()), 3); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### or_else example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use or_else to handle errors by calling a closure that returns a Result. The closure is only called if 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)); ``` -------------------------------- ### map_or_else example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::map_or_else to apply a fallback function to the Err value or a function to the Ok value. ```rust let k = 21; let x : Result<_, &str> = Ok("foo"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3); let x : Result<&str, _> = Err("bar"); assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42); ``` -------------------------------- ### get_prefix: Get current prefix Source: https://docs.rs/z80emu/latest/src/z80emu/z80.rs.html Returns the current pending prefix as an Option. Used to inspect the state of the emulator. ```rust #[inline] fn get_prefix(&self) -> Option { self.prefix } ``` -------------------------------- ### map_or example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::map_or to provide a default value for Err or apply a function to the Ok value. Note that arguments are eagerly evaluated. ```rust let x: Result<_, &str> = Ok("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Result<&str, _> = Err("bar"); assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Sum example: sum integers, reject on negative element Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use the Sum trait on Result to sum integers from a vector, returning an Err if any element is negative. ```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)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### ArrayVec::is_full example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Checks if the ArrayVec is completely filled to its capacity. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::<_, 1>::new(); assert!(!array.is_full()); array.push(1); assert!(array.is_full()); ``` -------------------------------- ### ArrayVec::is_empty example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Checks if the ArrayVec is empty after popping the only element. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::from([1]); array.pop(); assert_eq!(array.is_empty(), true); ``` -------------------------------- ### ArrayVec::remaining_capacity example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Returns the capacity left in the ArrayVec after popping an element. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::from([1, 2, 3]); array.pop(); assert_eq!(array.remaining_capacity(), 1); ``` -------------------------------- ### pub fn from_flavour(cpu: Z80) -> Self where Q: From Source: https://docs.rs/z80emu/latest/z80emu/z80/struct.Z80.html Converts between instances of Z80 with different flavours. Some Flavour related information may be lost during conversion. ```APIDOC ## `pub fn from_flavour(cpu: Z80) -> Self where Q: From` ### Description Converts between instances of Z80 with different flavours. **NOTE**: Some Flavour related information may be lost during conversion. ### Signature `pub fn from_flavour(cpu: Z80) -> Self where Q: From` ### Parameters - **cpu** (Z80) - The Z80 instance to convert from. ### Returns `Self` - A Z80 instance with the target flavour `Q`. ``` -------------------------------- ### ArrayVec::capacity example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Returns the capacity of the ArrayVec, which is the number of elements it can hold. ```rust use arrayvec::ArrayVec; let array = ArrayVec::from([1, 2, 3]); assert_eq!(array.capacity(), 3); ``` -------------------------------- ### unwrap_err panic example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Demonstrates that unwrap_err panics with the Ok content when the Result is Ok. ```rust let x: Result = Ok(2); x.unwrap_err(); // panics with `2` ``` -------------------------------- ### pub fn new() -> Self Source: https://docs.rs/z80emu/latest/z80emu/z80/struct.Z80.html Creates a new instance of Z80 with the state just after RESET. ```APIDOC ## `pub fn new() -> Self` ### Description Creates a new instance of Z80 with the state just after `RESET`. ### Signature `pub fn new() -> Self` ### Parameters None ### Returns `Self` - A new Z80 instance. ``` -------------------------------- ### pub flavour: Q Source: https://docs.rs/z80emu/latest/z80emu/z80/struct.Z80.html Exposes an instance of the Flavour implementation. ```APIDOC ## Field: `pub flavour: Q` ### Description Exposes an instance of the Flavour implementation. ### Type `Q` where `Q: Flavour` ``` -------------------------------- ### ArrayVec::len example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Returns the number of elements in the ArrayVec after popping one element. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::from([1, 2, 3]); array.pop(); assert_eq!(array.len(), 2); ``` -------------------------------- ### Z80::new Source: https://docs.rs/z80emu/latest/src/z80emu/z80.rs.html Creates a new instance of Z80 with the state just after RESET. ```APIDOC ## Z80::new ### Description Creates a new instance of Z80 with the state just after RESET. ### Method new ### Signature pub fn new() -> Self ### Parameters None ### Returns - **Self** - A new Z80 instance in the reset state. ``` -------------------------------- ### unwrap_err success example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows that unwrap_err returns the contained Err value when the Result is Err. ```rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Format CpuDebugArg Index and Port Addresses Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Demonstrates how to format index-based memory addresses and immediate ports using standard and hex-formatted strings. ```rust let arg = CpuDebugArg::Addr(CpuDebugAddr::IndexAddr(Prefix::Xdd, Some(127))); assert_eq!(arg.to_string(), "(IX+127)"); assert_eq!(format!("{:x}", arg), "(IX+7fh)"); assert_eq!(format!("{:X}", arg), "(IX+7Fh)"); assert_eq!(format!("{:#x}", arg), "(IX+0x7f)"); assert_eq!(format!("{:#X}", arg), "(IX+0x7F)"); let arg = CpuDebugArg::Addr(CpuDebugAddr::IndexAddr(Prefix::Yfd, None)); assert_eq!(arg.to_string(), "(IY)"); let arg = CpuDebugArg::Addr(CpuDebugAddr::IndexAddr(Prefix::Yfd, Some(-127))); assert_eq!(arg.to_string(), "(IY-127)"); assert_eq!(format!("{:x}", arg), "(IY-7fh)"); assert_eq!(format!("{:X}", arg), "(IY-7Fh)"); assert_eq!(format!("{:#x}", arg), "(IY-0x7f)"); assert_eq!(format!("{:#X}", arg), "(IY-0x7F)"); let arg = CpuDebugArg::Port(CpuDebugPort::ImmPort(254)); assert_eq!(arg.to_string(), "(254)"); assert_eq!(format!("{:x}", arg), "(feh)"); assert_eq!(format!("{:X}", arg), "(FEh)"); assert_eq!(format!("{:#x}", arg), "(0xfe)"); assert_eq!(format!("{:#X}", arg), "(0xFE)"); ``` -------------------------------- ### ArrayVec::push example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Pushes elements to the end of the vector. Panics if the vector is already full. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::<_, 2>::new(); array.push(1); array.push(2); assert_eq!(&array[..], &[1, 2]); ``` -------------------------------- ### ArrayVec::new_const example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Creates a new empty ArrayVec in a const context using new_const. ```rust use arrayvec::ArrayVec; static ARRAY: ArrayVec = ArrayVec::new_const(); ``` -------------------------------- ### Formatting CpuDebug with Display Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Shows how to format a CpuDebug value as text using format_args!. The output shows the program counter, mnemonic, and byte code. ```rust format_args!("{}", deb) ``` -------------------------------- ### Format CpuDebugArgs Collections Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Demonstrates string formatting for various argument combinations including registers, immediate values, and bit operations. ```rust assert_eq!(CpuDebugArgs::None.to_string(), ""); assert_eq!(CpuDebugArgs::Single(CpuDebugArg::I).to_string(), "I"); assert_eq!(CpuDebugArgs::Double(CpuDebugArg::Reg8(None, Reg8::A), CpuDebugArg::R).to_string(), "A, R"); let arg = CpuDebugArgs::Double(CpuDebugArg::Stk16(StkReg16::AF), CpuDebugArg::Stk16(StkReg16::AF)); assert_eq!(arg.to_string(), "AF, AF'"); let arg = CpuDebugArgs::Double(CpuDebugArg::Imm16(32767), CpuDebugArg::Addr(CpuDebugAddr::ImmAddr(65535))); assert_eq!(arg.to_string(), "32767, (65535)"); assert_eq!(format!("{:x}", arg), "7fffh, (ffffh)"); assert_eq!(format!("{:X}", arg), "7FFFh, (FFFFh)"); assert_eq!(format!("{:#x}", arg), "0x7fff, (0xffff)"); assert_eq!(format!("{:#X}", arg), "0x7FFF, (0xFFFF)"); let arg = CpuDebugArgs::BitOpExt(4, CpuDebugArg::Imm8(255), Reg8::C); assert_eq!(arg.to_string(), "4, 255, C"); assert_eq!(format!("{:x}", arg), "4, ffh, C"); assert_eq!(format!("{:X}", arg), "4, FFh, C"); assert_eq!(format!("{:#x}", arg), "4, 0xff, C"); assert_eq!(format!("{:#X}", arg), "4, 0xFF, C"); ``` -------------------------------- ### From> for Z80Any Source: https://docs.rs/z80emu/latest/z80emu/z80/any/enum.Z80Any.html Converts a Z80 to Z80Any. ```APIDOC ## From> for Z80Any ### Description Converts a Z80 to Z80Any. ### Method fn from(cpu: Z80) -> Z80Any ### Parameters - **cpu** (Z80) - Required - The Z80 CPU to convert. ### Returns - **Z80Any** - The converted Z80Any. ``` -------------------------------- ### macro_rules! forward_host_io_methods Source: https://docs.rs/z80emu/latest/z80emu/macro.forward_host_io_methods.html Defines a macro that forwards I/O methods to a wrapped instance. It accepts patterns to forward all combined methods, a curated set, or a specific I/O method. ```APIDOC ## Macro forward_host_io_methods ### Description Forwards methods of the `Io` trait to a wrapped instance. ### Method Signatures - `(@ => |$this:ident| $fwd:expr)` – Forward all methods. - `(($($func:ident)*) => |$this:ident| $fwd:expr)` – Forward a space-separated list of methods. - `(($($func:ident),*) => |$this:ident| $fwd:expr)` – Forward a comma-separated list of methods. - `(write_io => |$this:ident| $fwd:expr)` – Forward the `write_io` method. - `(read_io => |$this:ident| $fwd:expr)` – Forward the `read_io` method. - `(is_irq => |$this:ident| $fwd:expr)` – Forward the `is_irq` method. - `(irq_data => |$this:ident| $fwd:expr)` – Forward the `irq_data` method. - `(reti => |$this:ident| $fwd:expr)` – Forward the `reti` method. ### Parameters - `$this:ident` – Identifier for the current instance. - `$fwd:expr` – Expression that evaluates to the wrapped instance. - `$func:ident` – (in list variants) Identifier of the method to forward. ### Examples Refer to the `macros` module documentation. ``` -------------------------------- ### Convert and Assert Z80Any BM1 and NMOS variants Source: https://docs.rs/z80emu/latest/src/z80emu/z80/any.rs.html Demonstrates converting a Z80Any instance to BM1, verifying its tag and properties, and subsequently converting it to an NMOS variant. ```rust let cpu_any = cpu_any.into_bm1(); assert_eq!(cpu_any.tag(), "BM1"); assert_eq!(cpu_any, Z80Any::with_tag(BM1::tag()).unwrap()); assert_eq!(cpu_any, Z80Any::new_bm1()); assert_eq!(cpu_any.is_nmos(), false); assert_eq!(cpu_any.is_cmos(), false); assert_eq!(cpu_any.is_bm1(), true); let cpu = cpu_any.clone().unwrap_bm1(); assert_eq!(cpu_any, Z80Any::BM1(cpu)); let cpu_any = cpu_any.into_nmos(); assert_eq!(cpu_any.tag(), "NMOS"); assert_eq!(cpu_any, Z80Any::new_nmos()); } } ``` -------------------------------- ### ArrayVec::try_push example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Pushes elements and returns a Result, allowing handling of overflow without panicking. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::<_, 2>::new(); let push1 = array.try_push(1); let push2 = array.try_push(2); assert!(push1.is_ok()); assert!(push2.is_ok()); assert_eq!(&array[..], &[1, 2]); let overflow = array.try_push(3); assert!(overflow.is_err()); ``` -------------------------------- ### Z80Any::default Source: https://docs.rs/z80emu/latest/src/z80emu/z80/any.rs.html Creates a default Z80Any instance, which is the NMOS variant. ```APIDOC ## Z80Any::default ### Description Creates a default Z80Any instance, which is the NMOS variant. ### Method default ### Signature fn default() -> Z80Any ### Returns - **Z80Any** - A new Z80Any instance with the NMOS variant. ``` -------------------------------- ### From for Z80 Source: https://docs.rs/z80emu/latest/z80emu/z80/any/enum.Z80Any.html Converts a Z80Any to Z80. ```APIDOC ## From for Z80 ### Description Converts a Z80Any to Z80. ### Method fn from(cpu_any: Z80Any) -> Z80 where Q: Flavour + From + From + From ### Parameters - **cpu_any** (Z80Any) - Required - The Z80Any to convert. ### Returns - **Z80** - The converted Z80. ``` -------------------------------- ### map_err example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::map_err to transform the error type while leaving Ok values untouched. ```rust fn stringify(x: u32) -> String { format!("error code: {x}") } let x: Result = Ok(2); assert_eq!(x.map_err(stringify), Ok(2)); let x: Result = Err(13); assert_eq!(x.map_err(stringify), Err("error code: 13".to_string())); ``` -------------------------------- ### Cpu::reset Source: https://docs.rs/z80emu/latest/z80emu/trait.Cpu.html Instantly resets the Cpu to its initial state. ```APIDOC ## Cpu::reset ### Description Instantly resets the Cpu to its initial state. ### Method reset ### Signature fn reset(&mut self) ### Parameters None ### Returns None ``` -------------------------------- ### Input/Output timing diagram Source: https://docs.rs/z80emu/latest/src/z80emu/host.rs.html Diagram showing the timing for I/O cycles, including potential wait states. ```text T1 T2 TW T3 _ _ _ _ _ | |_| |_| |_| |_| |_| 0 ^ IO_CYCLE_TS ^ IO_IORQ_LOW_TS A0-15 |-----port------| D0-7 |----data---| IORQ -----__________-- RD -----__________-- (read) WR -----__________-- (write) WAIT .........__...... <===============> Io::read_io/write_io ^ Io::is_irq ¹ INT ............___.. ¹ ``` -------------------------------- ### unwrap_err_unchecked on Ok (undefined behavior) Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows that calling unwrap_err_unchecked on an Ok is undefined behavior. This example is for illustration only and should not be used in practice. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### unwrap_unchecked on Err (undefined behavior) Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows that calling unwrap_unchecked on an Err is undefined behavior. This example is for illustration only and should not be used in practice. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Z80::from_flavour Source: https://docs.rs/z80emu/latest/src/z80emu/z80.rs.html Converts between instances of Z80 with different flavours. ```APIDOC ## Z80::from_flavour ### Description Converts between instances of Z80 with different flavours. ### Method from_flavour ### Signature pub fn from_flavour(cpu: Z80) -> Self where Q: From ### Parameters - **cpu** (Z80) - Required - The Z80 instance to convert from. ### Returns - **Self** - A new Z80 instance with the current flavour. ``` -------------------------------- ### impl Clone for Z80 Source: https://docs.rs/z80emu/latest/z80emu/z80/type.Z80NMOS.html Provides cloning functionality for the Z80 CPU instance. ```APIDOC ## Clone for Z80 ### Description Provides cloning functionality for the Z80 CPU instance. ### Methods #### fn clone(&self) -> Z80 Returns a duplicate of the value. #### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. ``` -------------------------------- ### inspect_err example Source: https://docs.rs/z80emu/latest/z80emu/host/type.Result.html Shows how to use Result::inspect_err to call a function with a reference to the Err value, returning the original result. ```rust use std::{fs, io}; fn read() -> io::Result { fs::read_to_string("address.txt") .inspect_err(|e| eprintln!("failed to read file: {e}")) } ``` -------------------------------- ### IN Instruction Implementation Source: https://docs.rs/z80emu/latest/src/z80emu/z80/instructions.rs.html Handles input operations from I/O ports. ```rust ( IN A,(n) @@@ $code:expr) => { { // pc+1:3, IO let n: u8 = fetch_next_imm8!(); cpu_debug!([$code, n] IN r:A, port:n); $cpu.io_a_inp_an($control, $tsc, n); // let port: u16 = ($cpu.af.get8hi() as u16) << 8 | n as u16; // // MEMPTR = (A_before_operation << 8) + port + 1 // $cpu.memptr.set16(port.wrapping_add(1)); // let (data, wait_states) = $control.read_io(port, $tsc.add_io(port)); // if let Some(ws) = wait_states { // $tsc.add_wait_states(port, ws); // } // $cpu.af.set8hi(data); } }; ( IN r,(C) @@@ $code0:expr, $code1:expr) => { { // IO let arg = Reg8::from_b5_3($code1); ``` -------------------------------- ### Test flavour conversion and Z80Any wrapping Source: https://docs.rs/z80emu/latest/src/z80emu/z80/flavours.rs.html Tests flavour conversion between Z80, Z80, and Z80 using into_flavour() and from_flavour(). Also verifies that Z80Any::from() correctly wraps each flavour variant. ```rust let cmos: Z80 = Z80::::default().into_flavour(); let nmos = Z80::::from_flavour(cmos); let bm1 = nmos.into_flavour::(); assert_eq!(bm1, Z80::::default()); let cmos1: Z80 = Z80::::default(); let cmos2: Z80 = Z80::::default(); assert_eq!(Z80Any::from(cmos1), Z80Any::CMOS(cmos2)); let nmos1: Z80 = Z80::::default(); let nmos2: Z80 = Z80::::default(); assert_eq!(Z80Any::from(nmos1), Z80Any::NMOS(nmos2)); let bm1_1: Z80 = Z80::::default(); let bm1_2: Z80 = Z80::::default(); assert_eq!(Z80Any::from(bm1_1), Z80Any::BM1(bm1_2)); ``` -------------------------------- ### Implement fmt::Display for CpuDebug Source: https://docs.rs/z80emu/latest/src/z80emu/cpu/debug.rs.html Provides a standard string representation for CpuDebug. ```rust impl fmt::Display for CpuDebug { #[inline(never)] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:>5} {:4} {:14} {:?}", self.pc, self.mnemonic, self.args, self.code.as_slice()) } } ``` -------------------------------- ### Z80::into_flavour Source: https://docs.rs/z80emu/latest/src/z80emu/z80.rs.html Converts between instances of Z80 with different flavours. ```APIDOC ## Z80::into_flavour ### Description Converts between instances of Z80 with different flavours. ### Method into_flavour ### Signature pub fn into_flavour(self) -> Z80 where F: From ### Parameters None ### Returns - **Z80** - A new Z80 instance with the specified flavour. ``` -------------------------------- ### take Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Returns the ArrayVec, replacing the original with a new empty ArrayVec. ```APIDOC ## take ### Description Returns the ArrayVec, replacing the original with a new empty ArrayVec. ### Signature pub fn take(&mut self) -> ArrayVec ### Example ```rust use arrayvec::ArrayVec; let mut v = ArrayVec::from([0, 1, 2, 3]); assert_eq!([0, 1, 2, 3], v.take().into_inner().unwrap()); assert!(v.is_empty()); ``` ``` -------------------------------- ### ArrayVec::insert example Source: https://docs.rs/z80emu/latest/z80emu/type.CpuDebugCode.html Inserts an element at a given index, shifting subsequent elements. Panics if the array is full or the index is out of bounds. ```rust use arrayvec::ArrayVec; let mut array = ArrayVec::<_, 2>::new(); array.insert(0, "x"); array.insert(0, "y"); assert_eq!(&array[..], &["y", "x"]); ```