#memory-management #byte #size #memory-size

memory_size

A crate with the ability to represent a number of bits or bytes, and apply arithmetic to the sizes

1 unstable release

new 0.1.0 Apr 15, 2025

#38 in #memory-management

43 downloads per month

GPL-3.0-or-later

15KB
276 lines

This crate provides the MemorySize type, a wrapper around a memory size represented in bits. It supports basic arithmetic operations and pretty-printing in human-readable formats.

Usage Example

use memory_size::MemorySize;

// Create a MemorySize from bytes
let size = MemorySize::from_bytes(1024);
println!("Size: {}", size); // prints "1.00 KB" (depending on the chosen format)

Memory Size

MemorySize is a Rust library for representing a number of bits or bytes. It provides utilities for working with memory sizes in bytes and bits, as well as performing arithmetic operations, comparisons, and formatting.

Features

  • Create memory sizes from bytes or bits.
  • Perform arithmetic operations (+, -, +=, -=) on memory sizes.
  • Compare memory sizes using PartialOrd and Ord.
  • Pretty-print memory sizes in human-readable formats (e.g. 10 kB, 1 GB).
  • Clamp, find the maximum, or find the minimum of memory sizes.
  • Sum memory sizes from iterators.

Example

use memory_size::MemorySize;

fn main() {
    let size1 = MemorySize::from_bytes(1024); // 1 KB
    let size2 = MemorySize::from_bytes(2048); // 2 KB

    let total = size1 + size2;
    println!("Total size: {}", total); // Output: Total size: 3 kB
}

Testing

To run the testing scripts, use:

cargo test

Dependencies

~0.6–1.1MB
~24K SLoC