Skip to main content

wiwi_memory_usage/impls/
string.rs

1use crate::macros::impl_memory_usage;
2
3impl_memory_usage! {
4	str |self| self.len();
5}
6
7#[cfg(feature = "std")]
8impl_memory_usage! {
9	// todo this is only dyn because shrink is not const
10	dyn String
11	|self| size_of::<String>() + self.capacity();
12	compacted |self| self.capacity() - self.len();
13	compact |self| {
14		let old_cap = self.capacity();
15		self.shrink_to_fit();
16		old_cap - self.len()
17	};
18	// can't do anything to compact string behind a ref
19	// not getting any benefit from calling it on the u8s lmao
20}
21
22#[cfg(test)]
23mod tests {
24	#[cfg(feature = "std")]
25	use crate::{ MemoryCompaction as _, MemoryUsageStatic as _ };
26	use crate::MemoryUsage as _;
27
28	#[test]
29	fn str_usage() {
30		let str = "awawawa";
31
32		assert_eq!(str.memory_usage(), 7);
33	}
34
35	#[cfg(feature = "std")]
36	#[test]
37	fn string_usage() {
38		let string_size = <*const u8>::MEMORY_USAGE + usize::MEMORY_USAGE + usize::MEMORY_USAGE;
39
40		let mut string = String::with_capacity(247);
41		let string_capacity = string.capacity();
42		string.push_str("awawawa");
43		let expected = string_size + string_capacity;
44		let expected_compacted = string_size + 7;
45		let expected_compact = expected - expected_compacted;
46
47		assert_eq!(string.memory_usage(), expected);
48		assert_eq!(string.memory_usage_compacted(), expected_compact);
49		assert_eq!(string.compact_memory(), expected_compact);
50	}
51}