From 6e293d029bd60f5565bb18629e3baf2d049e53cf Mon Sep 17 00:00:00 2001 From: Christian Cunningham Date: Wed, 24 Aug 2022 19:29:00 -0700 Subject: *cargo fmt --- build.rs | 32 ++--- src/_arch/arm/asm.rs | 24 ++-- src/console.rs | 78 +++++------ src/cpu.rs | 2 +- src/draw.rs | 38 +++--- src/kernel.rs | 140 ++++++++++--------- src/mem/alloc.rs | 360 +++++++++++++++++++++++-------------------------- src/mem/types.rs | 50 +++---- src/panic_wait.rs | 40 +++--- src/print.rs | 6 +- src/uart.rs | 186 ++++++++++++------------- src/util/fifo_queue.rs | 273 +++++++++++++++++++------------------ 12 files changed, 615 insertions(+), 614 deletions(-) diff --git a/build.rs b/build.rs index 721d6d6..cab00bb 100644 --- a/build.rs +++ b/build.rs @@ -1,20 +1,20 @@ -use std::{env,fs,process}; +use std::{env, fs, process}; fn main() { - let ld_script_path = match env::var("LD_SCRIPT_PATH") { - Ok(var) => var, - _ => process::exit(0), - }; + let ld_script_path = match env::var("LD_SCRIPT_PATH") { + Ok(var) => var, + _ => process::exit(0), + }; - let files = fs::read_dir(ld_script_path).unwrap(); - files - .filter_map(Result::ok) - .filter(|d| { - if let Some(e) = d.path().extension() { - e == "ld" - } else { - false - } - }) - .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); + let files = fs::read_dir(ld_script_path).unwrap(); + files + .filter_map(Result::ok) + .filter(|d| { + if let Some(e) = d.path().extension() { + e == "ld" + } else { + false + } + }) + .for_each(|f| println!("cargo:rerun-if-changed={}", f.path().display())); } diff --git a/src/_arch/arm/asm.rs b/src/_arch/arm/asm.rs index 5d53aa0..f767e08 100644 --- a/src/_arch/arm/asm.rs +++ b/src/_arch/arm/asm.rs @@ -7,40 +7,34 @@ /// # Wait for event #[inline(always)] pub fn wfe() { - unsafe { - core::arch::asm!("wfe", options(nomem, nostack)) - } + unsafe { core::arch::asm!("wfe", options(nomem, nostack)) } } /// # No Operation #[inline(always)] pub fn nop() { - unsafe { - core::arch::asm!("nop", options(nomem, nostack)) - } + unsafe { core::arch::asm!("nop", options(nomem, nostack)) } } /// # Store u32 to memory address #[inline] pub fn store32(addr: u32, value: u32) { - unsafe { - *(addr as *mut u32) = value; - } + unsafe { + *(addr as *mut u32) = value; + } } /// # Read u32 from memory address #[inline] pub fn load32(addr: u32) -> u32 { - unsafe { - *(addr as *mut u32) - } + unsafe { *(addr as *mut u32) } } /// # Spin CPU for `n` cycles #[inline] pub fn spin_for_n_cycles(n: u32) { - unsafe { - core::arch::asm!("1: subs r1, #1 + unsafe { + core::arch::asm!("1: subs r1, #1 bne 1b", in("r1") n); - } + } } diff --git a/src/console.rs b/src/console.rs index 1a732a7..ae3e62b 100644 --- a/src/console.rs +++ b/src/console.rs @@ -1,5 +1,5 @@ //! # UART Console module -//! +//! //! ## Encapsulates base trait for any console. //! ## Wraps the UART console. @@ -7,49 +7,51 @@ /// /// ## Provides trait for consoles. pub mod interface { - use core::fmt; - /// # Write Trait - /// - /// Structure must provide ways to: - /// - Write individual characters - /// - Write formatted strings - /// - Flush write queue - pub trait Write { - /// # Write Character - /// - /// Writes an individual character to a console - fn write_char(&self, c: char); - /// # Write Format - /// - /// Writes a formatted string to a console - fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; - /// # Flush - /// - /// Flush console write queue - fn flush(&self); - } + use core::fmt; + /// # Write Trait + /// + /// Structure must provide ways to: + /// - Write individual characters + /// - Write formatted strings + /// - Flush write queue + pub trait Write { + /// # Write Character + /// + /// Writes an individual character to a console + fn write_char(&self, c: char); + /// # Write Format + /// + /// Writes a formatted string to a console + fn write_fmt(&self, args: fmt::Arguments) -> fmt::Result; + /// # Flush + /// + /// Flush console write queue + fn flush(&self); + } - /// # Statistics Trait - /// - /// Structure must provide a way to: - /// - Get how many characters have been written - pub trait Statistics { - /// # Get Written Chars - /// - /// Gets the statistic associated with how many - /// characters have been written to a console. - fn chars_written(&self) -> usize { 0 } - } + /// # Statistics Trait + /// + /// Structure must provide a way to: + /// - Get how many characters have been written + pub trait Statistics { + /// # Get Written Chars + /// + /// Gets the statistic associated with how many + /// characters have been written to a console. + fn chars_written(&self) -> usize { + 0 + } + } - /// # All Trait - /// - /// Structure must provide both Write + Statistics - pub trait All: Write + Statistics {} + /// # All Trait + /// + /// Structure must provide both Write + Statistics + pub trait All: Write + Statistics {} } /// # UART console /// /// Returns a borrow for the UART writer pub fn console() -> &'static crate::uart::Uart { - &crate::uart::UART_WRITER + &crate::uart::UART_WRITER } diff --git a/src/cpu.rs b/src/cpu.rs index 26efd52..669f5f2 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -7,4 +7,4 @@ mod boot; /// # Low-level bindings /// /// Re-export low-level bindings -pub use arch_cpu::{nop,wait_forever,spin_for_n_cycles,load32,store32}; +pub use arch_cpu::{load32, nop, spin_for_n_cycles, store32, wait_forever}; diff --git a/src/draw.rs b/src/draw.rs index 2af00fa..907aa5c 100644 --- a/src/draw.rs +++ b/src/draw.rs @@ -4,26 +4,26 @@ use crate::println; pub fn draw_american_flag() { - println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); - println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); - println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); - println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); - println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); - println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); - println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); - println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); - println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); - println!("\x1b[107m \x1b[0m"); - println!("\x1b[101m \x1b[0m"); - println!("\x1b[107m \x1b[0m"); - println!("\x1b[101m \x1b[0m"); + println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); + println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); + println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); + println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); + println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); + println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); + println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); + println!("\x1b[97;104m * * * * * \x1b[107m \x1b[0m"); + println!("\x1b[97;104m * * * * * * \x1b[101m \x1b[0m"); + println!("\x1b[107m \x1b[0m"); + println!("\x1b[101m \x1b[0m"); + println!("\x1b[107m \x1b[0m"); + println!("\x1b[101m \x1b[0m"); } pub fn draw_ukraine_flag() { - println!("\x1b[30;104m \x1b[0m"); - println!("\x1b[30;104m Slava \x1b[0m"); - println!("\x1b[30;104m \x1b[0m"); - println!("\x1b[30;103m \x1b[0m"); - println!("\x1b[30;103m Ukraina \x1b[0m"); - println!("\x1b[30;103m \x1b[0m"); + println!("\x1b[30;104m \x1b[0m"); + println!("\x1b[30;104m Slava \x1b[0m"); + println!("\x1b[30;104m \x1b[0m"); + println!("\x1b[30;103m \x1b[0m"); + println!("\x1b[30;103m Ukraina \x1b[0m"); + println!("\x1b[30;103m \x1b[0m"); } diff --git a/src/kernel.rs b/src/kernel.rs index e92c701..24de020 100644 --- a/src/kernel.rs +++ b/src/kernel.rs @@ -4,10 +4,11 @@ //! - UART //! - Allocators -#![doc(html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png")] - +#![doc( + html_logo_url = "https://raw.githubusercontent.com/rust-embedded/wg/master/assets/logo/ewg-logo-blue-white-on-transparent.png" +)] #![allow(non_snake_case)] -#![allow(clippy::upper_case_acronyms,dead_code)] +#![allow(clippy::upper_case_acronyms, dead_code)] #![feature(format_args_nl)] #![feature(panic_info_message)] #![feature(trait_alias)] @@ -19,8 +20,8 @@ extern crate alloc; pub use alloc::boxed::Box; -pub use alloc::string::String; pub use alloc::format; +pub use alloc::string::String; mod console; mod cpu; @@ -41,7 +42,7 @@ use crate::mem::alloc::allocator; /// - Box /// - String /// - format! -/// - UART +/// - UART /// - print! /// - println! /// - vprint! @@ -50,74 +51,87 @@ use crate::mem::alloc::allocator; /// After initialization, jump to /// the regular main. unsafe fn kernel_init() -> ! { - console().init().unwrap(); - allocator().init().unwrap(); - kernel_main() + console().init().unwrap(); + allocator().init().unwrap(); + kernel_main() } /// # Post-initialization /// /// TODO: Figure out what to do here fn kernel_main() -> ! { - #[cfg(not(feature="verbose"))] - { - #[cfg(feature="flag")] - { - draw::draw_ukraine_flag(); - println!(); - draw::draw_american_flag(); - println!(); - } + #[cfg(not(feature = "verbose"))] + { + #[cfg(feature = "flag")] + { + draw::draw_ukraine_flag(); + println!(); + draw::draw_american_flag(); + println!(); + } - println!("\x1b[91mInitialized\x1b[0m \x1b[92m{}\x1b[0m \x1b[93mv{}\x1b[0m", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); - println!("\x1b[94mAuthors:\x1b[0m \x1b[95m{}\x1b[0m", env!("CARGO_PKG_AUTHORS")); - use crate::console::interface::Statistics; - println!("Characters written to UART: \x1b[91m{}\x1b[0m", console().chars_written()); - } + println!( + "\x1b[91mInitialized\x1b[0m \x1b[92m{}\x1b[0m \x1b[93mv{}\x1b[0m", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + ); + println!( + "\x1b[94mAuthors:\x1b[0m \x1b[95m{}\x1b[0m", + env!("CARGO_PKG_AUTHORS") + ); + use crate::console::interface::Statistics; + println!( + "Characters written to UART: \x1b[91m{}\x1b[0m", + console().chars_written() + ); + } - #[cfg(feature="verbose")] - run_verbose(); + #[cfg(feature = "verbose")] + run_verbose(); - loop { } + loop {} } fn run_verbose() { - println!("U8: {:?}", mem::alloc::U8_GRAND_ALLOC); - { - let mut s = String::new(); - for _ in 0..128 { - s += "TEST"; - } - assert_eq!(s.capacity(), 512); - } - { - let s = format!("{:X}", 0xCAFEBABE as u32); - assert_eq!(s, "CAFEBABE"); - assert_eq!(s.capacity(), 8); - } - { - let a: Box = Box::new(1); - assert_eq!(*a, 1); - println!("{}", a); - } - { - let a: Box = Box::new(2); - let b: Box = Box::new(3); - let c: Box = Box::new(4); - assert_eq!(*a, 2); - assert_eq!(*b, 3); - assert_eq!(*c, 4); - println!("{} {} {}", a, b, c); - } - { - let a: Box = Box::new(5); - let b: Box = Box::new(6); - let c: Box = Box::new(7); - assert_eq!(*a, 5); - assert_eq!(*b, 6); - assert_eq!(*c, 7); - println!("{} {} {}", a, b, c); - } - use crate::console::interface::Statistics; - println!("Characters written to UART: \x1b[91m{}\x1b[0m", console().chars_written()); + println!("U8: {:?}", mem::alloc::U8_GRAND_ALLOC); + { + let mut s = String::new(); + for _ in 0..128 { + s += "TEST"; + } + assert_eq!(s.capacity(), 512); + } + { + let s = format!("{:X}", 0xCAFEBABE as u32); + assert_eq!(s, "CAFEBABE"); + assert_eq!(s.capacity(), 8); + } + { + let a: Box = Box::new(1); + assert_eq!(*a, 1); + println!("{}", a); + } + { + let a: Box = Box::new(2); + let b: Box = Box::new(3); + let c: Box = Box::new(4); + assert_eq!(*a, 2); + assert_eq!(*b, 3); + assert_eq!(*c, 4); + println!("{} {} {}", a, b, c); + } + { + let a: Box = Box::new(5); + let b: Box = Box::new(6); + let c: Box = Box::new(7); + assert_eq!(*a, 5); + assert_eq!(*b, 6); + assert_eq!(*c, 7); + println!("{} {} {}", a, b, c); + } + use crate::console::interface::Statistics; + println!( + "Characters written to UART: \x1b[91m{}\x1b[0m", + console().chars_written() + ); } diff --git a/src/mem/alloc.rs b/src/mem/alloc.rs index a98e680..a388c85 100644 --- a/src/mem/alloc.rs +++ b/src/mem/alloc.rs @@ -2,20 +2,20 @@ //! //! Provides the Global allocator and methods //! to create special purpose allocators. -use alloc::alloc::{GlobalAlloc,Layout}; -use crate::sync::NullLock; +use super::types::*; use crate::sync::interface::Mutex; +use crate::sync::NullLock; use crate::vprintln; -use super::types::*; -use os_pic::util::node::Node; -use os_pic::util::lifo_queue::LifoQueue; +use alloc::alloc::{GlobalAlloc, Layout}; use os_pic::init_lifo_queue; +use os_pic::util::lifo_queue::LifoQueue; +use os_pic::util::node::Node; use os_pic::util::queue::Queue; /// # Grand Allocator /// /// The structure that uses different sized pools and allocates memory chunks -pub struct GrandAllocator { } +pub struct GrandAllocator {} /// # The number of elements of each size const GRAND_ALLOC_SIZE: usize = 64; @@ -25,160 +25,140 @@ init_lifo_queue!(U16_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u16); init_lifo_queue!(U32_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u32); init_lifo_queue!(U64_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u64); init_lifo_queue!(U128_GRAND_ALLOC, GRAND_ALLOC_SIZE, 0, u128); -init_lifo_queue!(U256_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U256::new()}, U256); -init_lifo_queue!(U512_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U512::new()}, U512); -init_lifo_queue!(U1024_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U1024::new()}, U1024); -init_lifo_queue!(U2048_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U2048::new()}, U2048); -init_lifo_queue!(U4096_GRAND_ALLOC, GRAND_ALLOC_SIZE, {U4096::new()}, U4096); +init_lifo_queue!(U256_GRAND_ALLOC, GRAND_ALLOC_SIZE, { U256::new() }, U256); +init_lifo_queue!(U512_GRAND_ALLOC, GRAND_ALLOC_SIZE, { U512::new() }, U512); +init_lifo_queue!(U1024_GRAND_ALLOC, GRAND_ALLOC_SIZE, { U1024::new() }, U1024); +init_lifo_queue!(U2048_GRAND_ALLOC, GRAND_ALLOC_SIZE, { U2048::new() }, U2048); +init_lifo_queue!(U4096_GRAND_ALLOC, GRAND_ALLOC_SIZE, { U4096::new() }, U4096); impl GrandAllocator { - pub fn init(&self) -> Result<(), &'static str> { - vprintln!("GA: \x1b[93mInit U8 Pool\x1b[0m"); - U8_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U16 Pool\x1b[0m"); - U16_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U32 Pool\x1b[0m"); - U32_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U64 Pool\x1b[0m"); - U64_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U128 Pool\x1b[0m"); - U128_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U256 Pool\x1b[0m"); - U256_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U512 Pool\x1b[0m"); - U512_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U1024 Pool\x1b[0m"); - U1024_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U2048 Pool\x1b[0m"); - U2048_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[93mInit U4096 Pool\x1b[0m"); - U4096_GRAND_ALLOC.init(); - vprintln!("GA: \x1b[94mPools Initialized!\x1b[0m"); - Ok(()) - } + pub fn init(&self) -> Result<(), &'static str> { + vprintln!("GA: \x1b[93mInit U8 Pool\x1b[0m"); + U8_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U16 Pool\x1b[0m"); + U16_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U32 Pool\x1b[0m"); + U32_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U64 Pool\x1b[0m"); + U64_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U128 Pool\x1b[0m"); + U128_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U256 Pool\x1b[0m"); + U256_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U512 Pool\x1b[0m"); + U512_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U1024 Pool\x1b[0m"); + U1024_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U2048 Pool\x1b[0m"); + U2048_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[93mInit U4096 Pool\x1b[0m"); + U4096_GRAND_ALLOC.init(); + vprintln!("GA: \x1b[94mPools Initialized!\x1b[0m"); + Ok(()) + } } unsafe impl GlobalAlloc for GrandAllocator { - /// # Allocator - /// - /// Allocate the fixed size chunks - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - vprintln!("GA: Allocating chunk of size {}!", layout.size()); - match layout.size() { - 1 => { - match U8_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 2 => { - match U16_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 3..=4 => { - match U32_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 5..=8 => { - match U64_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 9..=16 => { - match U128_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 17..=32 => { - match U256_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 33..=64 => { - match U512_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 65..=128 => { - match U1024_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 129..=256 => { - match U2048_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - 257..=512 => { - match U4096_GRAND_ALLOC.pop() { - None => { - panic!("No cells to allocate!"); - } - Some(elem) => { - return (*elem).ptr(); - } - } - } - _ => { - panic!("No allocators for size {}!", layout.size()); - } - } - } + /// # Allocator + /// + /// Allocate the fixed size chunks + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + vprintln!("GA: Allocating chunk of size {}!", layout.size()); + match layout.size() { + 1 => match U8_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 2 => match U16_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 3..=4 => match U32_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 5..=8 => match U64_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 9..=16 => match U128_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 17..=32 => match U256_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 33..=64 => match U512_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 65..=128 => match U1024_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 129..=256 => match U2048_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + 257..=512 => match U4096_GRAND_ALLOC.pop() { + None => { + panic!("No cells to allocate!"); + } + Some(elem) => { + return (*elem).ptr(); + } + }, + _ => { + panic!("No allocators for size {}!", layout.size()); + } + } + } - /// # Deallocate - /// - /// Deallocate the fixed size chunks by searching for them - unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - vprintln!("GA: Deallocating chunk of size {}!", layout.size()); - match layout.size() { - 1 => { - U8_GRAND_ALLOC.inner.lock(|pool| { + /// # Deallocate + /// + /// Deallocate the fixed size chunks by searching for them + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + vprintln!("GA: Deallocating chunk of size {}!", layout.size()); + match layout.size() { + 1 => { + U8_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -187,9 +167,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U8_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 2 => { - U16_GRAND_ALLOC.inner.lock(|pool| { + } + 2 => { + U16_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -198,9 +178,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U16_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 3..=4 => { - U32_GRAND_ALLOC.inner.lock(|pool| { + } + 3..=4 => { + U32_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -209,9 +189,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U32_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 5..=8 => { - U64_GRAND_ALLOC.inner.lock(|pool| { + } + 5..=8 => { + U64_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -220,9 +200,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U64_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 9..=16 => { - U128_GRAND_ALLOC.inner.lock(|pool| { + } + 9..=16 => { + U128_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -231,9 +211,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U128_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 17..=32 => { - U256_GRAND_ALLOC.inner.lock(|pool| { + } + 17..=32 => { + U256_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -242,9 +222,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U256_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 33..=64 => { - U512_GRAND_ALLOC.inner.lock(|pool| { + } + 33..=64 => { + U512_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -253,9 +233,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U512_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 65..=128 => { - U1024_GRAND_ALLOC.inner.lock(|pool| { + } + 65..=128 => { + U1024_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -264,9 +244,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U1024_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 129..=256 => { - U2048_GRAND_ALLOC.inner.lock(|pool| { + } + 129..=256 => { + U2048_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -275,9 +255,9 @@ unsafe impl GlobalAlloc for GrandAllocator { U2048_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - 257..=512 => { - U4096_GRAND_ALLOC.inner.lock(|pool| { + } + 257..=512 => { + U4096_GRAND_ALLOC.inner.lock(|pool| { let spacing: usize = (pool[2].ptr() as usize) - (pool[1].ptr() as usize); let diff: usize = (ptr as usize) - (pool[1].ptr() as usize); let index: usize = diff/spacing; @@ -286,24 +266,24 @@ unsafe impl GlobalAlloc for GrandAllocator { U4096_GRAND_ALLOC.push(&mut pool[index+1]); vprintln!("GA: Freeing ({}, {}, {})", index, diff, spacing); }); - } - _ => { - panic!("No deallocators for size {}!", layout.size()); - } - } - } + } + _ => { + panic!("No deallocators for size {}!", layout.size()); + } + } + } } /// # Grand Allocator /// /// The allocator of allocators. It hands out fixed sized memory chunks. #[global_allocator] -pub static ALLOCATOR: GrandAllocator = GrandAllocator{}; +pub static ALLOCATOR: GrandAllocator = GrandAllocator {}; /// # Global Allocator /// /// Returns a borrow for the Global Allocator pub fn allocator() -> &'static crate::mem::alloc::GrandAllocator { - vprintln!("AL: Getting global allocator!"); - &crate::mem::alloc::ALLOCATOR + vprintln!("AL: Getting global allocator!"); + &crate::mem::alloc::ALLOCATOR } diff --git a/src/mem/types.rs b/src/mem/types.rs index 04522bc..ed22132 100644 --- a/src/mem/types.rs +++ b/src/mem/types.rs @@ -1,54 +1,54 @@ /// # u256 struct /// /// 256 bit size field -#[derive(Copy,Clone)] -pub struct U256(u128,u128); +#[derive(Copy, Clone)] +pub struct U256(u128, u128); impl U256 { - pub const fn new() -> Self { - U256(0,0) - } + pub const fn new() -> Self { + U256(0, 0) + } } /// # u512 struct /// /// 512 bit size field -#[derive(Copy,Clone)] -pub struct U512(U256,U256); +#[derive(Copy, Clone)] +pub struct U512(U256, U256); impl U512 { - pub const fn new() -> Self { - U512(U256::new(), U256::new()) - } + pub const fn new() -> Self { + U512(U256::new(), U256::new()) + } } /// # u1024 struct /// /// 1024 bit size field -#[derive(Copy,Clone)] -pub struct U1024(U512,U512); +#[derive(Copy, Clone)] +pub struct U1024(U512, U512); impl U1024 { - pub const fn new() -> Self { - U1024(U512::new(), U512::new()) - } + pub const fn new() -> Self { + U1024(U512::new(), U512::new()) + } } /// # u2048 struct /// /// 2048 bit size field -#[derive(Copy,Clone)] -pub struct U2048(U1024,U1024); +#[derive(Copy, Clone)] +pub struct U2048(U1024, U1024); impl U2048 { - pub const fn new() -> Self { - U2048(U1024::new(), U1024::new()) - } + pub const fn new() -> Self { + U2048(U1024::new(), U1024::new()) + } } /// # u4096 struct /// /// 4096 bit size field -#[derive(Copy,Clone)] -pub struct U4096(U2048,U2048); +#[derive(Copy, Clone)] +pub struct U4096(U2048, U2048); impl U4096 { - pub const fn new() -> Self { - U4096(U2048::new(), U2048::new()) - } + pub const fn new() -> Self { + U4096(U2048::new(), U2048::new()) + } } diff --git a/src/panic_wait.rs b/src/panic_wait.rs index a9dfba3..53998a0 100644 --- a/src/panic_wait.rs +++ b/src/panic_wait.rs @@ -2,7 +2,7 @@ //! //! A panic handler that infinitely waits -use crate::{cpu,println}; +use crate::{cpu, println}; use core::panic::PanicInfo; /// # Prevent Double Faulting @@ -12,28 +12,34 @@ use core::panic::PanicInfo; /// there was already a fault, it spins to /// prevent a recursive faulting cycle. fn panic_prevent_reenter() { - use core::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, Ordering}; - static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); + static PANIC_IN_PROGRESS: AtomicBool = AtomicBool::new(false); - if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { - PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); - return; - } + if !PANIC_IN_PROGRESS.load(Ordering::Relaxed) { + PANIC_IN_PROGRESS.store(true, Ordering::Relaxed); + return; + } - cpu::wait_forever() + cpu::wait_forever() } /// # Panic handler #[panic_handler] fn panic(info: &PanicInfo) -> ! { - panic_prevent_reenter(); - - let (location, line, column) = match info.location() { - Some(loc) => (loc.file(), loc.line(), loc.column()), - _ => ("???",0,0), - }; - - println!("Kernel panic!\n\nPanic Location:\n\tFile: '{}', line {}, column {}\n\n{}", location, line, column, info.message().unwrap_or(&format_args!("")),); - cpu::wait_forever() + panic_prevent_reenter(); + + let (location, line, column) = match info.location() { + Some(loc) => (loc.file(), loc.line(), loc.column()), + _ => ("???", 0, 0), + }; + + println!( + "Kernel panic!\n\nPanic Location:\n\tFile: '{}', line {}, column {}\n\n{}", + location, + line, + column, + info.message().unwrap_or(&format_args!("")), + ); + cpu::wait_forever() } diff --git a/src/print.rs b/src/print.rs index 1598378..2fefd91 100644 --- a/src/print.rs +++ b/src/print.rs @@ -1,13 +1,13 @@ //! # Printing to UART //! //! This module contains the macros to print formatted strings to UART. -use core::fmt; -use crate::uart::UART_WRITER; use crate::console::interface::Write; +use crate::uart::UART_WRITER; +use core::fmt; #[doc(hidden)] pub fn _print(args: fmt::Arguments) { - UART_WRITER.write_fmt(args).unwrap(); + UART_WRITER.write_fmt(args).unwrap(); } /// # Print without newline diff --git a/src/uart.rs b/src/uart.rs index 0f66116..fa516a8 100644 --- a/src/uart.rs +++ b/src/uart.rs @@ -1,138 +1,138 @@ //! # UART Console Definition use crate::cpu::*; +use crate::sync::interface::Mutex; use crate::sync::NullLock; use core::fmt; -use crate::sync::interface::Mutex; /// # Data Register -const UART0_DR: u32 = 0x3F201000; +const UART0_DR: u32 = 0x3F201000; /// # Flag Register -const UART0_FR: u32 = 0x3F201018; +const UART0_FR: u32 = 0x3F201018; /// # Fractional Baud Rate Register -const UART0_FBRD: u32 = 0x3F201028; +const UART0_FBRD: u32 = 0x3F201028; /// # Line Control Register -const UART0_LCRH: u32 = 0x3F20102C; +const UART0_LCRH: u32 = 0x3F20102C; /// # Control Register -const UART0_CR: u32 = 0x3F201030; +const UART0_CR: u32 = 0x3F201030; /// # Interrupt Mask Set/ Clear Register -const UART0_IMSC: u32 = 0x3F201038; +const UART0_IMSC: u32 = 0x3F201038; /// # Interrupt Control Register -const UART0_ICR: u32 = 0x3F201044; +const UART0_ICR: u32 = 0x3F201044; /// # Integer Baud Rate Register -const UART0_IBRD: u32 = 0x3F201024; +const UART0_IBRD: u32 = 0x3F201024; /// GPIO Register -const GPPUD: u32 = 0x3F200094; +const GPPUD: u32 = 0x3F200094; /// GPIO Clock 0 Register -const GPPUDCLK0: u32 = 0x3F200098; +const GPPUDCLK0: u32 = 0x3F200098; /// # UART Inner Structure /// /// Keeps record of the console statistics. struct UartInner { - chars_written: usize, + chars_written: usize, } /// # UART Structure /// /// Wraps the UART writer in a sharable lock. pub struct Uart { - inner: NullLock, + inner: NullLock, } impl UartInner { - /// # Clear statistics - /// - /// Create the writer with cleared statistics - pub const fn new() -> Self { - Self { - chars_written: 0, - } - } - - /// # Initialize the UART setup - /// - /// Set baud rate and timings - pub fn init(&mut self) { - store32(UART0_CR, 0); - store32(GPPUD, 0); - spin_for_n_cycles(150); - store32(GPPUDCLK0, (1 << 14) | (1 << 15)); - spin_for_n_cycles(150); - store32(GPPUDCLK0, 0); - store32(UART0_ICR, 0x7FF); - store32(UART0_IBRD, 9); - store32(UART0_FBRD, 49); - store32(UART0_LCRH, (1<<4) | (1<<5) | (1<<6)); - store32(UART0_IMSC, (1<<1) | (1<<4) | (1<<5) | (1<<6) | (1<<7) | (1<<8) | (1<<9) | (1<<10)); - store32(UART0_CR, (1<<0) | (1<<8) | (1<<9)); - } - - /// # Write `char` to UART - fn write_char(&mut self, ch: char) { - while load32(UART0_FR) & 0x20 != 0 { - nop(); - } - store32(UART0_DR, ch as u32); - self.chars_written += 1; - } - - /// # Flush UART - fn flush(&self) { - while load32(UART0_FR) & 0x08 != 0 { - nop(); - } - } + /// # Clear statistics + /// + /// Create the writer with cleared statistics + pub const fn new() -> Self { + Self { chars_written: 0 } + } + + /// # Initialize the UART setup + /// + /// Set baud rate and timings + pub fn init(&mut self) { + store32(UART0_CR, 0); + store32(GPPUD, 0); + spin_for_n_cycles(150); + store32(GPPUDCLK0, (1 << 14) | (1 << 15)); + spin_for_n_cycles(150); + store32(GPPUDCLK0, 0); + store32(UART0_ICR, 0x7FF); + store32(UART0_IBRD, 9); + store32(UART0_FBRD, 49); + store32(UART0_LCRH, (1 << 4) | (1 << 5) | (1 << 6)); + store32( + UART0_IMSC, + (1 << 1) | (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10), + ); + store32(UART0_CR, (1 << 0) | (1 << 8) | (1 << 9)); + } + + /// # Write `char` to UART + fn write_char(&mut self, ch: char) { + while load32(UART0_FR) & 0x20 != 0 { + nop(); + } + store32(UART0_DR, ch as u32); + self.chars_written += 1; + } + + /// # Flush UART + fn flush(&self) { + while load32(UART0_FR) & 0x08 != 0 { + nop(); + } + } } impl fmt::Write for UartInner { - /// # Write string to UART console - fn write_str(&mut self, s: &str) -> fmt::Result { - for c in s.chars() { - self.write_char(c); - } - Ok(()) - } + /// # Write string to UART console + fn write_str(&mut self, s: &str) -> fmt::Result { + for c in s.chars() { + self.write_char(c); + } + Ok(()) + } } - impl Uart { - /// # Create sharable UART wrapper - pub const fn new() -> Self { - Self { - inner: NullLock::new(UartInner::new()), - } - } - - /// # Call UART initialization - pub fn init(&self) -> Result<(), &'static str> { - self.inner.lock(|inner| inner.init()); - Ok(()) - } + /// # Create sharable UART wrapper + pub const fn new() -> Self { + Self { + inner: NullLock::new(UartInner::new()), + } + } + + /// # Call UART initialization + pub fn init(&self) -> Result<(), &'static str> { + self.inner.lock(|inner| inner.init()); + Ok(()) + } } impl super::console::interface::Write for Uart { - /// # Write `char` to UART - fn write_char(&self, c: char) { - self.inner.lock(|inner| inner.write_char(c)); - } - - /// # Write formatted string to UART - fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { - self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) - } - - /// # Flush UART - fn flush(&self) { - self.inner.lock(|inner| inner.flush()); - } + /// # Write `char` to UART + fn write_char(&self, c: char) { + self.inner.lock(|inner| inner.write_char(c)); + } + + /// # Write formatted string to UART + fn write_fmt(&self, args: core::fmt::Arguments) -> fmt::Result { + self.inner.lock(|inner| fmt::Write::write_fmt(inner, args)) + } + + /// # Flush UART + fn flush(&self) { + self.inner.lock(|inner| inner.flush()); + } } impl super::console::interface::Statistics for Uart { - /// # Get `char` written stats - fn chars_written(&self) -> usize { - self.inner.lock(|inner| inner.chars_written) - } + /// # Get `char` written stats + fn chars_written(&self) -> usize { + self.inner.lock(|inner| inner.chars_written) + } } /// # UART Writer + Stats diff --git a/src/util/fifo_queue.rs b/src/util/fifo_queue.rs index 744b7f9..42d63ac 100644 --- a/src/util/fifo_queue.rs +++ b/src/util/fifo_queue.rs @@ -1,11 +1,11 @@ //! # FIFO Queue //! //! Provides the FIFO queue structure for allocations -use crate::sync::NullLock; use crate::sync::interface::Mutex; +use crate::sync::NullLock; use crate::vprintln; use core::fmt; -use core::fmt::{Debug,Formatter}; +use core::fmt::{Debug, Formatter}; /// # Initialize Queue /// - Name: Symbol name @@ -24,163 +24,168 @@ macro_rules! init_queue { }; } -#[derive(Copy,Clone)] +#[derive(Copy, Clone)] /// # Queue Item /// /// Encapsulates a data element and a pointer to /// the next `Queue` item pub struct QueueItem<'a, T: Sized> { - /// # Data - /// - /// The encapsulated data - data: T, - /// # Pointer to the next item - /// - /// Stores either `None` or points - /// to the next item. - next: Option<*mut QueueItem<'a, T>>, + /// # Data + /// + /// The encapsulated data + data: T, + /// # Pointer to the next item + /// + /// Stores either `None` or points + /// to the next item. + next: Option<*mut QueueItem<'a, T>>, } -impl QueueItem<'_,T> { - /// # Constructor - pub const fn new(data: T) -> Self { - Self { - data: data, - next: None, - } - } - /// # Get the inner data - /// - /// Returns a borrow of the underlying data. - pub fn inner(&mut self) -> &mut T { - &mut self.data - } - /// # Get pointer to inner data - pub fn ptr(&mut self) -> *mut u8 { - self.inner() as *mut T as *mut u8 - } +impl QueueItem<'_, T> { + /// # Constructor + pub const fn new(data: T) -> Self { + Self { + data: data, + next: None, + } + } + /// # Get the inner data + /// + /// Returns a borrow of the underlying data. + pub fn inner(&mut self) -> &mut T { + &mut self.data + } + /// # Get pointer to inner data + pub fn ptr(&mut self) -> *mut u8 { + self.inner() as *mut T as *mut u8 + } } /// # Sharing Thread Safety for QueueItem -unsafe impl Send for QueueItem<'_,T> {} +unsafe impl Send for QueueItem<'_, T> {} -impl Debug for QueueItem<'_,T> { - /// # Debug formatter for `QueueItem` - /// - /// Output the encapsulated data - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - #[cfg(feature="verbose")] - return write!(f, "{:?} {:x} {:?}", self.data, self as *const QueueItem<'_,T> as usize, self.next); +impl Debug for QueueItem<'_, T> { + /// # Debug formatter for `QueueItem` + /// + /// Output the encapsulated data + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + #[cfg(feature = "verbose")] + return write!( + f, + "{:?} {:x} {:?}", + self.data, self as *const QueueItem<'_, T> as usize, self.next + ); - #[cfg(not(feature="verbose"))] - return write!(f, "{:?}", self.data); - } + #[cfg(not(feature = "verbose"))] + return write!(f, "{:?}", self.data); + } } /// # Queue Allocator /// /// Structure to store a pool of allocated data structures. pub struct QueueAllocator<'a, T: Sized, const COUNT: usize> { - /// # Synchronized Pool of items - /// - /// Stores synchronization wrapper around the data pool - pub inner: NullLock<[QueueItem<'a, T>;COUNT]>, + /// # Synchronized Pool of items + /// + /// Stores synchronization wrapper around the data pool + pub inner: NullLock<[QueueItem<'a, T>; COUNT]>, } /// # Sharing Thread Safety for QueueAllocator -unsafe impl Send for QueueAllocator<'_,T,COUNT> {} +unsafe impl Send for QueueAllocator<'_, T, COUNT> {} -impl<'a, T: Sized,const COUNT: usize> QueueAllocator<'a, T, COUNT> { - /// # Initialization of Fixed-Size Pool - /// - /// Establishes the header and footer of the queue - /// as the first and second elements respectively. - /// All of the internal elements point to the next - /// one and the final element points to `None` - pub fn init(&self) { - vprintln!("QA: Initializing Queue Allocator!"); - self.inner.lock(|queue| { - vprintln!("QA: Clearing internal references..."); - for idx in 2..COUNT { - if idx != COUNT-1 { - queue[idx].next = Some(&mut queue[idx+1] as *mut QueueItem<'a, T>); - } else { - queue[idx].next = None; - } - } - vprintln!("QA: Initializing head and tail..."); - queue[0].next = Some(&mut queue[2] as *mut QueueItem<'a, T>); - queue[1].next = Some(&mut queue[COUNT-1] as *mut QueueItem<'a, T>); - }); - vprintln!("QA: Initialized Queue Allocator!"); - } +impl<'a, T: Sized, const COUNT: usize> QueueAllocator<'a, T, COUNT> { + /// # Initialization of Fixed-Size Pool + /// + /// Establishes the header and footer of the queue + /// as the first and second elements respectively. + /// All of the internal elements point to the next + /// one and the final element points to `None` + pub fn init(&self) { + vprintln!("QA: Initializing Queue Allocator!"); + self.inner.lock(|queue| { + vprintln!("QA: Clearing internal references..."); + for idx in 2..COUNT { + if idx != COUNT - 1 { + queue[idx].next = Some(&mut queue[idx + 1] as *mut QueueItem<'a, T>); + } else { + queue[idx].next = None; + } + } + vprintln!("QA: Initializing head and tail..."); + queue[0].next = Some(&mut queue[2] as *mut QueueItem<'a, T>); + queue[1].next = Some(&mut queue[COUNT - 1] as *mut QueueItem<'a, T>); + }); + vprintln!("QA: Initialized Queue Allocator!"); + } - /// # Allocate Data - /// - /// If there is a data chunk available, - /// return it, otherwise return `None` - #[allow(dead_code)] - pub fn alloc(&self) -> Option<&mut QueueItem<'a,T>> { - vprintln!("QA: Allocating chunk!"); - return self.inner.lock(|pool| { - if let Some(entry) = pool[0].next { - vprintln!("QA: Found chunk!"); - pool[0].next = unsafe { (*entry).next }; - unsafe { - (*entry).next = None; - } - match pool[0].next { - None => { - pool[1].next = None - } - _ => {} - } - vprintln!("QA: \x1b[92mAllocated {:x}\x1b[0m", unsafe{(*entry).ptr() as usize}); - return Some(unsafe{&mut *entry as &mut QueueItem<'a,T>}); - } else { - vprintln!("QA: No chunks available!"); - return None; - } - }); - } + /// # Allocate Data + /// + /// If there is a data chunk available, + /// return it, otherwise return `None` + #[allow(dead_code)] + pub fn alloc(&self) -> Option<&mut QueueItem<'a, T>> { + vprintln!("QA: Allocating chunk!"); + return self.inner.lock(|pool| { + if let Some(entry) = pool[0].next { + vprintln!("QA: Found chunk!"); + pool[0].next = unsafe { (*entry).next }; + unsafe { + (*entry).next = None; + } + match pool[0].next { + None => pool[1].next = None, + _ => {} + } + vprintln!("QA: \x1b[92mAllocated {:x}\x1b[0m", unsafe { + (*entry).ptr() as usize + }); + return Some(unsafe { &mut *entry as &mut QueueItem<'a, T> }); + } else { + vprintln!("QA: No chunks available!"); + return None; + } + }); + } - /// # Free - /// - /// Add the item to the end of the queue. - /// If there were no items, set it as the head. - #[allow(dead_code)] - pub fn free(&self, freed_item: &mut QueueItem<'a,T>) { - vprintln!("QA: Deallocating chunk!"); - self.inner.lock(|pool| { - freed_item.next = None; - match pool[1].next { - None => { - pool[0].next = Some(freed_item as *mut QueueItem<'a,T>); - } - Some(entry) => { - unsafe { - (*entry).next = Some(freed_item as *mut QueueItem<'a,T>); - } - } - } - pool[1].next = Some(freed_item as *mut QueueItem<'a,T>); - vprintln!("QA: \x1b[91mDeallocated {:x}\x1b[0m", freed_item.ptr() as usize); - }); - } + /// # Free + /// + /// Add the item to the end of the queue. + /// If there were no items, set it as the head. + #[allow(dead_code)] + pub fn free(&self, freed_item: &mut QueueItem<'a, T>) { + vprintln!("QA: Deallocating chunk!"); + self.inner.lock(|pool| { + freed_item.next = None; + match pool[1].next { + None => { + pool[0].next = Some(freed_item as *mut QueueItem<'a, T>); + } + Some(entry) => unsafe { + (*entry).next = Some(freed_item as *mut QueueItem<'a, T>); + }, + } + pool[1].next = Some(freed_item as *mut QueueItem<'a, T>); + vprintln!( + "QA: \x1b[91mDeallocated {:x}\x1b[0m", + freed_item.ptr() as usize + ); + }); + } } -impl Debug for QueueAllocator<'_,T,COUNT> { - /// # Debug Formatted Output - /// - /// Output each data point in the array with - /// its debug formatter. - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - self.inner.lock(|queue| { - #[cfg(feature="verbose")] - return write!(f, "{:?}", queue); +impl Debug for QueueAllocator<'_, T, COUNT> { + /// # Debug Formatted Output + /// + /// Output each data point in the array with + /// its debug formatter. + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + self.inner.lock(|queue| { + #[cfg(feature = "verbose")] + return write!(f, "{:?}", queue); - #[cfg(not(feature="verbose"))] - return write!(f, "{:?}", queue); - }) - } + #[cfg(not(feature = "verbose"))] + return write!(f, "{:?}", queue); + }) + } } -- cgit v1.2.1