pebble
  • Tutorials
  • Get the SDK
  • Guides
  • Documentation
  • PebbleOS
  • Mobile App
  • Examples
  • Index 01
  • Community
  • Blog
  • More
Privacy
Cookies
Publish

PebbleOS

  • Overview
  • Start here
    • Getting started guide
    • Playground
  • Development
    • The pbl CLI
    • Build system
    • Samples
      • Threads
      • Mutexes
      • Semaphores
      • Message queues
      • Poll groups
      • Timers
      • Work queues
      • Delayed work
      • Heaps
      • Time
      • Idle states
      • Dining philosophers
      • Bounded buffer
      • Readers and writers
      • Sleeping barber
      • Priority inversion
      • Barrier
      • CRC
      • SHA-256
      • AES
      • Files
      • Settings
      • Translations
      • Input events
      • Loader
      • Log levels
      • Profiler
      • Shell commands
      • Task watchdog
      • Accelerometer
      • Ambient light
      • Backlight
      • Battery
      • Display
      • Flash
      • GPU
      • Magnetometer
      • Microphone
      • External RAM
      • Random numbers
      • Real-time clock
      • Speaker
      • Die temperature
      • Touchscreen
      • Vibration
      • Rust
      • Kernel benchmark
    • Emulator and simulator
    • Testing
    • Debugging
    • Conventions
  • System
    • Architecture overview
    • Kernel
    • Subsystems
    • Drivers
    • Services
    • Libraries
    • Third-party
    • Application SDK
  • Hardware
    • Boards
    • Programmers
  • Community
    • Contribution Guidelines
  • Reference
    • Reference
    • Kconfig options

Heap in Rust

The heap sample written in Rust, on the pebbleos crate.

Heap<N> sets itself up and takes a lock on first use; each Block it returns goes back to it when dropped, so freeing every other block is emptying every other slot of an array.

Run:

pbl samples samples/rust/kernel/heap

Boards:

every board

Sources

src/lib.rs
#![no_std]

use pebbleos::heap::{Block, Heap};
use pebbleos::{Errno, Result, println};

const BLOCK_SIZE: usize = 100;

// A heap of its own bounds what one user can take, here a 2 KiB cache.
static HEAP: Heap<2048> = Heap::new();

fn log_usage(when: &str) {
    let stats = HEAP.stats();
    println!(
        "heap: {when}: {} used, {} free, largest free block {}",
        stats.used, stats.free, stats.largest_free
    );
}

#[pebbleos::main]
fn main() -> Result<()> {
    let mut blocks: [Option<Block>; 32] = [const { None }; 32];

    log_usage("empty");

    // Allocation fails with None, which the caller handles.
    let name = HEAP
        .alloc_copy(b"a string on the heap")
        .ok_or(Errno::ENOMEM)?;
    println!(
        "heap: block is in the heap: {}, allocated: {}",
        yes_no(HEAP.contains(name.as_ptr())),
        yes_no(HEAP.is_allocated(name.as_ptr()))
    );
    // A block goes back to its heap when dropped.
    drop(name);

    let mut num_blocks = 0;
    for slot in &mut blocks {
        *slot = HEAP.alloc(BLOCK_SIZE);
        if slot.is_none() {
            break;
        }
        num_blocks += 1;
    }
    println!("heap: full after {num_blocks} blocks of {BLOCK_SIZE} bytes");
    log_usage("full");

    // Every other block freed: plenty of memory in total, but in pieces.
    for slot in blocks.iter_mut().step_by(2) {
        *slot = None;
    }
    log_usage("every other block freed");
    let big = HEAP.alloc(2 * BLOCK_SIZE);
    println!(
        "heap: {} bytes from a fragmented heap: {}",
        2 * BLOCK_SIZE,
        if big.is_none() {
            "refused"
        } else {
            "allocated"
        }
    );

    // Freed neighbors merge, so the pieces become one block again.
    drop(blocks);
    log_usage("all freed");

    println!(
        "heap: least memory it ever had left: {} of {} bytes",
        HEAP.min_headroom(),
        HEAP.size()
    );

    println!("Sample done");

    Ok(())
}

fn yes_no(b: bool) -> &'static str {
    if b { "yes" } else { "no" }
}

Output

heap: empty: 0 used, \d+ free, largest free block \d+
heap: block is in the heap: yes, allocated: yes
heap: full after \d+ blocks of 100 bytes
heap: full: \d+ used, \d+ free, largest free block \d+
heap: every other block freed: \d+ used, \d+ free, largest free block \d+
heap: 200 bytes from a fragmented heap: refused
heap: all freed: 0 used, \d+ free, largest free block \d+
heap: least memory it ever had left: \d+ of \d+ bytes
Sample done

Generated from PebbleOS 7753e801d. This page is maintained in the pebbleos repository: docs/samples/rust/kernel/heap.md.

Overview

  • Sources
  • Output