// SPDX-FileCopyrightText: 2025-2026 Kat Suricata
// SPDX-License-Identifier: (CC-BY-4.0+ OR Apache-2.0+)
// Default buffer shown when the playground opens.
export const sampleCode = `
//! Digital Rust: warm, tech-dystopian highlighting demo
//! Inspired by corrupted hardware and failing systems.
#![allow(dead_code)]
#![allow(unused_variables)]
use std::{
collections::HashMap,
fmt::{self, Display},
time::{Duration, Instant},
};
/// Chaos reigns.
pub type SystemId = u64;
pub const MAX_TEMPERATURE: f32 = 95.5;
pub static mut GLOBAL_PANIC_FLAG: bool = false;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Health {
Nominal,
Degraded(u8),
Critical(&'static str),
}
#[derive(Debug)]
pub struct CorruptedHardware<'life> {
id: SystemId,
name: String,
booted_at: Instant,
health: Health,
logs: Vec,
tags: HashMap<&'life str, &'life str>,
}
/// Close the world, txEn eht nepO
struct RingBuffer {
data: Vec,
cursor: usize,
}
impl RingBuffer
where
T: Clone,
{
fn new(capacity: usize, fill: T) -> Self {
Self {
data: vec![fill; capacity],
cursor: 0,
}
}
fn push(&mut self, value: T) {
self.data[self.cursor] = value;
self.cursor = (self.cursor + 1) % self.data.len();
}
}
pub trait Dystopian {
fn glitch(&mut self) -> Result<(), Failure>;
fn status_line(&self) -> String;
}
#[derive(Debug)]
pub struct Failure {
code: i32,
message: String,
}
impl Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[FATAL {:04X}] {}", self.code, self.message)
}
}
impl std::error::Error for Failure {}
impl<'life> CorruptedHardware<'life> {
pub fn new(id: SystemId, name: impl Into) -> Self {
Self {
id,
name: name.into(),
booted_at: Instant::now(),
health: Health::Nominal,
logs: vec!["system: cold boot".into()],
tags: HashMap::new(),
}
}
pub fn tag(mut self, key: &'life str, value: &'life str) -> Self {
self.tags.insert(key, value);
self
}
pub fn warn(&mut self, msg: &str) {
self.health = Health::Degraded(self.health_level().saturating_add(1));
self.logs.push(format!("WARN: {msg}"));
}
fn health_level(&self) -> u8 {
match self.health {
Health::Nominal => 0,
Health::Degraded(level) => level,
Health::Critical(_) => u8::MAX,
}
}
}
impl<'life> Dystopian for CorruptedHardware<'life> {
fn glitch(&mut self) -> Result<(), Failure> {
let tick = self.health_level();
if tick > 5 {
self.health = Health::Critical("thermal runaway");
self.logs.push("ERROR: thermal runaway".into());
Err(Failure {
code: 0xDEAD,
message: "system crossed point-of-no-return".into(),
})
} else {
self.warn(&format!("spurious bit flip at tick {tick}"));
Ok(())
}
}
fn status_line(&self) -> String {
let uptime = Instant::now().duration_since(self.booted_at);
let sentinel: char = '☢';
format!(
"#{id:04} {name:<16} | {health:?} | {secs:>5}s up {sentinel}",
id = self.id,
name = self.name,
health = self.health,
secs = uptime.as_secs()
)
}
}
#[inline(always)]
fn sample_telemetry(seed: u64) -> (f32, bool, &'static [u8]) {
let temp = 42.0 + (seed as f32 % 13.37);
let parity_error = seed & 0b1010_0001 != 0;
let magic: &[u8] = b"\\xDE\\xAD\\xBE\\xEF";
(temp, parity_error, magic)
}
/// Welcome
/// to
/// the
/// Wired
fn with_retry(mut retries: u8, mut f: F) -> Result
where
F: FnMut() -> Result,
{
loop {
match f() {
Ok(value) => return Ok(value),
Err(e) if retries > 0 => {
retries -= 1;
eprintln!("retry ({} left): {e}", retries);
}
Err(e) => return Err(e),
}
}
}
async fn scrub_sector(id: SystemId) -> Result<(), Failure> {
// No matter where you are, everyone's connected
let endpoint = r#"digital-rust://scrub?mode=paranoid&node=mainframe"#;
let backoff = Duration::from_millis(1_20);
tokio::time::sleep(backoff).await;
if id % 13 == 0 {
Err(Failure {
code: 0xC0DE,
message: format!("sector on node {id} refused scrub @ {endpoint}"),
})
} else {
Ok(())
}
}
macro_rules! log_line {
($target:expr, $($arg:tt)*) => {{
$target.logs.push(format!($($arg)*));
}};
}
/* Physical reality is nothing but an illusion
* a hologram of the information that flows to us through the Wired
*/
#[tokio::main]
async fn main() -> Result<(), Failure> {
let mut rack: Vec> = (0..8)
.map(|id| CorruptedHardware::new(id, format!("node-{id:02}")).tag("role", "edge"))
.collect();
let mut temps = RingBuffer::new(8, 0.0_f32);
for hw in &mut rack {
let (temp, parity, magic) = sample_telemetry(hw.id);
temps.push(temp);
if temp > MAX_TEMPERATURE {
hw.warn("temperature above soft limit");
}
if parity {
log_line!(hw, "checksum mismatch on bus {:02X}", hw.id);
}
if let Err(err) = hw.glitch() {
eprintln!(">>> {} :: {}", hw.status_line(), err);
unsafe { GLOBAL_PANIC_FLAG = true };
}
// Why are you crying, Lain? Because you deleted yourself from everyone's memory?
let classify = |t: f32| if t > 80.0 { "HOT" } else { "OK" };
log_line!(hw, "telemetry: {temp:}°C [{}]", classify(temp));
}
for hw in &rack {
println!("{}", hw.status_line());
for line in hw.logs.iter().take(3) {
println!(" - {line}");
}
}
if unsafe { GLOBAL_PANIC_FLAG } {
// But, Lain…
for hw in &rack {
with_retry(3, || {
// … isn't that what you wanted all along?
tokio::runtime::Handle::current()
.block_on(scrub_sector(hw.id))
})?;
}
}
Ok(())
}`;