@@ -3,16 +3,30 @@ use std::fmt;
33
44use cfg_if:: cfg_if;
55
6+ #[ derive( Copy , Clone ) ]
67pub struct MemoryUsage {
78 pub allocated : Bytes ,
89}
910
11+ impl fmt:: Display for MemoryUsage {
12+ fn fmt ( & self , fmt : & mut fmt:: Formatter ) -> fmt:: Result {
13+ write ! ( fmt, "{}" , self . allocated)
14+ }
15+ }
16+
17+ impl std:: ops:: Sub for MemoryUsage {
18+ type Output = MemoryUsage ;
19+ fn sub ( self , rhs : MemoryUsage ) -> MemoryUsage {
20+ MemoryUsage { allocated : self . allocated - rhs. allocated }
21+ }
22+ }
23+
1024impl MemoryUsage {
1125 pub fn current ( ) -> MemoryUsage {
1226 cfg_if ! {
1327 if #[ cfg( target_os = "linux" ) ] {
1428 // Note: This is incredibly slow.
15- let alloc = unsafe { libc:: mallinfo( ) } . uordblks as u32 as usize ;
29+ let alloc = unsafe { libc:: mallinfo( ) } . uordblks as u32 as isize ;
1630 MemoryUsage { allocated: Bytes ( alloc) }
1731 } else {
1832 MemoryUsage { allocated: Bytes ( 0 ) }
@@ -21,17 +35,11 @@ impl MemoryUsage {
2135 }
2236}
2337
24- impl fmt:: Display for MemoryUsage {
25- fn fmt ( & self , fmt : & mut fmt:: Formatter ) -> fmt:: Result {
26- write ! ( fmt, "{}" , self . allocated)
27- }
28- }
29-
3038#[ derive( Default , PartialEq , Eq , PartialOrd , Ord , Hash , Clone , Copy ) ]
31- pub struct Bytes ( usize ) ;
39+ pub struct Bytes ( isize ) ;
3240
3341impl Bytes {
34- pub fn megabytes ( self ) -> usize {
42+ pub fn megabytes ( self ) -> isize {
3543 self . 0 / 1024 / 1024
3644 }
3745}
@@ -41,10 +49,10 @@ impl fmt::Display for Bytes {
4149 let bytes = self . 0 ;
4250 let mut value = bytes;
4351 let mut suffix = "b" ;
44- if value > 4096 {
52+ if value. abs ( ) > 4096 {
4553 value /= 1024 ;
4654 suffix = "kb" ;
47- if value > 4096 {
55+ if value. abs ( ) > 4096 {
4856 value /= 1024 ;
4957 suffix = "mb" ;
5058 }
@@ -55,7 +63,7 @@ impl fmt::Display for Bytes {
5563
5664impl std:: ops:: AddAssign < usize > for Bytes {
5765 fn add_assign ( & mut self , x : usize ) {
58- self . 0 += x;
66+ self . 0 += x as isize ;
5967 }
6068}
6169
0 commit comments