diff --git a/firmware/qemu/src/bin/alloc.out b/firmware/qemu/src/bin/alloc.out index 16bab3d4..e94e483d 100644 --- a/firmware/qemu/src/bin/alloc.out +++ b/firmware/qemu/src/bin/alloc.out @@ -9,3 +9,7 @@ 0.000008 INFO Vec<Box<i32>>: [-1, 2, 3, 4] 0.000009 INFO Box<Vec<i32>>: [-1, 2, 3, 4] 0.000010 INFO String: Hello! I'm a heap-allocated String +0.000011 INFO Cow<[u32]>: [1, 2, 3, 4] +0.000012 INFO Cow<Vec<u32>>: [1, 2, 3, 4] +0.000013 INFO Cow<str>: moo +0.000014 INFO Cow<String>: moo, but allocated diff --git a/firmware/qemu/src/bin/alloc.release.out b/firmware/qemu/src/bin/alloc.release.out index 16bab3d4..e94e483d 100644 --- a/firmware/qemu/src/bin/alloc.release.out +++ b/firmware/qemu/src/bin/alloc.release.out @@ -9,3 +9,7 @@ 0.000008 INFO Vec<Box<i32>>: [-1, 2, 3, 4] 0.000009 INFO Box<Vec<i32>>: [-1, 2, 3, 4] 0.000010 INFO String: Hello! I'm a heap-allocated String +0.000011 INFO Cow<[u32]>: [1, 2, 3, 4] +0.000012 INFO Cow<Vec<u32>>: [1, 2, 3, 4] +0.000013 INFO Cow<str>: moo +0.000014 INFO Cow<String>: moo, but allocated diff --git a/firmware/qemu/src/bin/alloc.rs b/firmware/qemu/src/bin/alloc.rs index 6c865292..8fad17d4 100644 --- a/firmware/qemu/src/bin/alloc.rs +++ b/firmware/qemu/src/bin/alloc.rs @@ -4,6 +4,7 @@ extern crate alloc; +use alloc::borrow::Cow; use alloc::boxed::Box; use alloc::rc::Rc; use alloc::string::String; @@ -37,6 +38,10 @@ fn main() -> ! { "String: {=?}", String::from("Hello! I'm a heap-allocated String") ); + defmt::info!("Cow<[u32]>: {=?}", Cow::from(&[1u32, 2, 3, 4][..])); + defmt::info!("Cow<Vec<u32>>: {=?}", Cow::from(vec![1u32, 2, 3, 4])); + defmt::info!("Cow<str>: {=?}", Cow::from("moo")); + defmt::info!("Cow<String>: {=?}", String::from("moo, but allocated")); loop { debug::exit(debug::EXIT_SUCCESS) diff --git a/src/impls.rs b/src/impls.rs index 8a4c8191..338c1296 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -447,6 +447,22 @@ mod if_alloc { self.as_str().format(f) } } + + impl<'a, T> Format for alloc::borrow::Cow<'a, [T]> + where + T: 'a + Format, + [T]: alloc::borrow::ToOwned<Owned = alloc::vec::Vec<T>>, + { + fn format(&self, f: Formatter) { + self.as_ref().format(f) + } + } + + impl<'a> Format for alloc::borrow::Cow<'a, str> { + fn format(&self, f: Formatter) { + self.as_ref().format(f) + } + } } impl Format for core::convert::Infallible {