~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/zkwid

0
0
main
100 lines · 2.4 KB Raw History
#![no_std]

use core::arch::wasm32::unreachable;

const BUF: usize = 4096;

static mut INPUT: [u8; BUF] = [0; BUF];
static mut OUTPUT: [u8; BUF] = [0; BUF];

#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
    unreachable()
}

#[unsafe(no_mangle)]
pub extern "C" fn input_ptr() -> *mut u8 {
    (&raw mut INPUT).cast()
}

#[unsafe(no_mangle)]
pub extern "C" fn output_ptr() -> *mut u8 {
    (&raw mut OUTPUT).cast()
}

#[unsafe(no_mangle)]
pub extern "C" fn run(len: i32) -> i32 {
    let len = match usize::try_from(len) {
        Ok(len) if len <= BUF => len,
        _ => unreachable(),
    };
    let input = unsafe { core::slice::from_raw_parts((&raw const INPUT).cast::<u8>(), len) };
    let output = unsafe { core::slice::from_raw_parts_mut(output_ptr(), BUF) };
    let (Some(instance), Some(created_at)) =
        (field(input, b"instance"), field(input, b"createdAt"))
    else {
        unreachable()
    };
    let mut out = Writer {
        buf: output,
        pos: 0,
    };
    out.put(b"{\"$type\":\"at.zkwid.demo.log\",\"text\":\"hello from ");
    out.put(instance);
    out.put(b"\",\"createdAt\":\"");
    out.put(created_at);
    out.put(b"\"}");
    out.pos as i32
}

struct Writer<'a> {
    buf: &'a mut [u8],
    pos: usize,
}

impl Writer<'_> {
    fn put(&mut self, bytes: &[u8]) {
        let end = self.pos + bytes.len();
        if end > self.buf.len() {
            unreachable()
        }
        self.buf[self.pos..end].copy_from_slice(bytes);
        self.pos = end;
    }
}

fn field<'a>(json: &'a [u8], key: &[u8]) -> Option<&'a [u8]> {
    let mut i = 0;
    while i < json.len() {
        if json[i] == b'"' {
            let (s, next) = string(json, i)?;
            i = skip_ws(json, next);
            if json.get(i) == Some(&b':') {
                i = skip_ws(json, i + 1);
                if json.get(i) == Some(&b'"') {
                    let (v, next) = string(json, i)?;
                    if s == key {
                        return Some(v);
                    }
                    i = next;
                }
            }
        } else {
            i += 1;
        }
    }
    None
}

fn string(json: &[u8], start: usize) -> Option<(&[u8], usize)> {
    let rest = &json[start + 1..];
    let end = rest.iter().position(|&b| b == b'"')?;
    Some((&rest[..end], start + end + 2))
}

fn skip_ws(json: &[u8], mut i: usize) -> usize {
    while json.get(i).is_some_and(|b| b.is_ascii_whitespace()) {
        i += 1;
    }
    i
}