Projects

rejectsynth

from 2023 using Rust and VSCode

A programming language for composing music inside of a code editor, using a notation focusing on music theory. You can hear notes as you type them in, or select a passage to hear it played back.

solsolver

from 2022 using Rust, Python and OpenCV

I couldn't beat this really hard solitaire game, so I wrote a solver using the A* algorithm and wrote an auto-player using computer vision and mouse automation.

stdless

from 2022 using Rust and Linux syscalls

A minimal functioning webserver that has no dependencies besides the Rust language and Linux itself.

A learning exercise for exploring Linux syscalls and no_std + unsafe Rust. All of the networking and IO are implemented directly as syscalls using inline x86_64 assembly.

main.rs
#![feature(lang_items)]
#![feature(maybe_uninit_uninit_array)]
#![no_std]
#![no_main]

// Rust standard library
// (Vec, String, Everything you
// would want to use...)
//
// |-> no_std (Our project right now)
// |   -> Kernel
// |      (directly through Syscalls)
// |      (Linux)
// |
// |   For a syscall, you dump
// |   arguments into registers
// |   You dump a syscall NUMBER
// |   into the "RAX" register
// |   Call the "syscall" instruction
// |
// |-> std (not using this)
//     -> libc (C standard library)
//        (malloc, memcpy, memset)
//        |
//        | communicate with the
//        | operating system and with
//        | the hardware
//        v
//        Kernel (Linux)

mod linux;

use core::::PanicInfo;
use ;

const ROOT_INDEX: &'static [u8] = b"index.htm";

// LLVM depends on these functions, so we need these or else we get linker errors
#[no_mangle]
fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
    for i in 0..n {
        unsafe {
            *dest.add(i) = *src.add(i);
        }
    }
    dest
}

#[no_mangle]
fn memset(s: *mut u8, c: i32, n: usize) -> *mut u8 {
    for i in 0..n {
        unsafe {
            *s.add(i) = c as u8;
        }
    }
    s
}

fn write_num(fd: i32, mut num: usize) {
    if num == 0 {
        return (fd, &[b'0']);
    }
    const BUFFER_SIZE: usize = 10;
    let mut buffer: [u8; BUFFER_SIZE] = [0u8; BUFFER_SIZE];
    let mut i = BUFFER_SIZE;
    while num > 0 {
        if i == 0 {
            panic!("overflowed buffer for content length");
        } else {
            i -= 1;
        }

        let this_digit = (num % 10) as u8;
        num /= 10;
        buffer[i] = this_digit + b'0';
    }
    (fd, &buffer[i..BUFFER_SIZE]);
}

const NOT_FOUND_MSG: &[u8] = b"<marquee>404 Page Not Found</marquee>";

fn write_http_resp_from_filename(out_fd: i32, filename: &[u8]) {
    let fd = (filename);
    if fd.is_none() {
        (out_fd, 404, .len());
        (out_fd, );
        return;
    }

    let fd = fd.unwrap();
    let stats = (fd);
    (out_fd, 200, stats.st_size as _);

    let mut buf: [u8; 32] = [0u8; 32];
    loop {
        let bytes_read = (fd, &mut buf);
        if bytes_read > 0 {
            (out_fd, &buf[..bytes_read as _]);
        } else {
            break;
        }
    }
    (fd);
}

fn write_http_resp_header(fd: i32, code: usize, len: usize) {
    (fd, br#"HTTP/1.0 "#);
    (fd, code);
    (
        fd,
        br#" OK
Content-type: text/html; charset=UTF-8
Content-Length: "#,
    );
    (fd, len);
    (fd, b"\n\n");
}

fn extract_path_from_http_req(req: &[u8]) -> &[u8] {
    let mut i = 0;
    while req[i] != b' ' {
        i += 1;
    }

    #[allow(unused)]
    let request_method = &req[0..i];

    // skip the next char which is a space
    i += 1;

    // skip the leading / in the request, because that won't map to the filesystem
    if req[i] == b'/' {
        i += 1;
    }
    let start_of_path = i;
    while req[i] != b' ' && i < req.len() - 2 {
        i += 1;
    }
    &req[start_of_path..i]
}

#[no_mangle]
fn _start() {
    const PORT: u16 = 8080;
    ("Webserver listening on port ");
    (, PORT as _);
    ("...\n");

    let fd = ();
    (fd, PORT);
    (fd);
    // main web request loop
    loop {
        let conn_fd = (fd);

        // parse the request
        const REQ_BUF_SIZE: usize = 1024;
        let mut req_buf: [u8; REQ_BUF_SIZE] =
            unsafe { core::mem::MaybeUninit::uninit().assume_init() };
        let num_bytes_read = (conn_fd, &mut req_buf);
        let req = &req_buf[..num_bytes_read as _];
        let requested_path = (req);

        (, b"Read ");
        (, num_bytes_read as _);
        (, b" bytes:\n");
        (, &req_buf[..num_bytes_read as _]);
        // end of parse the request

        if requested_path.is_empty() {
            (conn_fd, );
        } else {
            (conn_fd, requested_path);
        }
        ("Send response to client who connected\n");
    }
}

fn htons(port: u16) -> u16 {
    port.to_be()
}

fn print(s: &str) {
    (, s.as_bytes());
}

#[panic_handler]
fn panic(panic_info: &PanicInfo<'_>) -> ! {
    // TODO: print out panic.location.file, line_number, etc.
    const STDERR: i32 = 2;
    (STDERR, b"\n\n\npanic! at ");
    match panic_info.location() {
        None => {}
        Some(loc) => {
            (STDERR, loc.file().as_bytes());
            (STDERR, b":");
            (STDERR, loc.line() as _);
            (STDERR, b":");
            (STDERR, loc.column() as _);
            (STDERR, b"\n");
        }
    }
    (1);
}
linux.rs
// linux syscalls layer

use core::arch::asm;
use core::mem::size_of;

type SocklenT = u32;
const AF_INET: i32 = 2;

pub fn read(fd: i32, buf: &mut [u8]) -> u32 {
    const SYSCALL_READ: u64 = 0;
    let res: i64;
    unsafe {
        //  ssize_t read(int fd, void *buf, size_t count);
        asm!(
        "syscall",
        inout("rax") SYSCALL_READ => res,
        // argument #1
        in("rdi") fd,
        // argument #2
        in("rsi") buf.as_ptr(),
        // argument #2
        in("rdx") buf.len(),
        )
    }

    if res < 0 {
        panic!("read failed");
    }
    res as u32
}

pub fn close(fd: i32) {
    const SYSCALL_CLOSE: u64 = 3;
    let res: i64;
    unsafe {
        // int close(int fd);
        asm!(
        "syscall",
        inout("rax") SYSCALL_CLOSE => res,
        // argument #1
        in("rdi") fd,
        )
    }

    if res < 0 {
        panic!("close failed");
    }
}

pub fn open(path: &[u8]) -> Option<i32> {
    // converting a rust string into a c string
    const BUFFER_SIZE: usize = 1024;
    let mut buffer: [u8; BUFFER_SIZE] = unsafe { core::mem::MaybeUninit::uninit().assume_init() };
    let path_bytes = path;
    if path_bytes.len() + 1 > BUFFER_SIZE {
        panic!("path is too long");
    }
    buffer[0..path_bytes.len()].copy_from_slice(path_bytes);
    buffer[path.len()] = 0;

    let fd: i32;
    let filepath_cstr = &buffer as *const u8;

    const SYSCALL_OPEN: i32 = 2;
    const O_RDONLY: i32 = 0;

    unsafe {
        // int open(char *file, int omode)
        asm!(
        "syscall",
        inout("rax") SYSCALL_OPEN => fd,
        // argument #1
        in("rdi") filepath_cstr,
        // argument #2
        in("rsi") O_RDONLY,
        )
    }

    if fd < 0 {
        None
    } else {
        Some(fd)
    }
}

// copilot wrote this struct, we can grab the size, not sure if it's even the correct size
// so maybe fstat is like writing into garbage memory because the struct isn't big enough
#[repr(C)]
#[derive(Default)]
pub struct Stat {
    st_dev: u64,
    st_ino: u64,
    st_nlink: u64,
    st_mode: u32,
    st_uid: u32,
    st_gid: u32,
    _pad0: u32,
    st_rdev: u64,
    pub st_size: i64,
    st_blksize: i64,
    st_blocks: i64,
    st_atime: u64,
    st_atime_nsec: u64,
    st_mtime: u64,
    st_mtime_nsec: u64,
    st_ctime: u64,
    st_ctime_nsec: u64,
    _unused: [i64; 3],
}

// fstat => 5
pub fn fstat(fd: i32) ->  {
    const SYSCALL_FSTAT: i32 = 5;
    let mut stat = ::default();
    let mut res: i32;
    unsafe {
        // int fstat(int fd, struct stat *buf)
        asm!(
        "syscall",
        inout("rax") SYSCALL_FSTAT => res,
        // argument #1
        in("rdi") fd,
        // argument #2
        in("rsi") &mut stat as *mut ,
        )
    }

    if res < 0 {
        panic!("stat failed");
    }
    stat
}

pub fn accept(fd: i32) -> i32 {
    const SYSCALL_ACCEPT: i32 = 43;
    let sockaddr_in =  {
        sin_family: 0,
        sin_port: 0,
        sin_addr: 0,
        sin_zero: [0, 0, 0, 0, 0, 0, 0, 0],
    };
    let sockaddr_in_ptr = &sockaddr_in as *const ;
    let sizeof_sockaddr_in = size_of::<>() as ;
    let sizeof_sockaddr_in_ptr = &sizeof_sockaddr_in as *const ;
    let mut ret;
    unsafe {
        asm!(
            "syscall",
            inout("rax") SYSCALL_ACCEPT => ret,
            in("rdi") fd,
            in("rsi") sockaddr_in_ptr,
            in("rdx") sizeof_sockaddr_in_ptr,
        );
    }
    ret
}

pub fn bind(fd: i32, port: u16) {
    const SYSCALL_BIND: u64 = 49;
    let sockaddr_in =  {
        sin_family:  as _,
        sin_port: (port),
        // listen on 0.0.0.0
        sin_addr: 0,
        // padding
        sin_zero: [0, 0, 0, 0, 0, 0, 0, 0],
    };
    let sockaddr_in_ptr = &sockaddr_in as *const ;
    let sizeof_sockaddr_in = size_of::<>();
    unsafe {
        asm!(
            "syscall",
            in("rax") SYSCALL_BIND,
            in("rdi") fd,
            in("rsi") sockaddr_in_ptr,
            in("rdx") sizeof_sockaddr_in,
        )
    }
}

pub fn listen(fd: i32) {
    const SYSCALL_LISTEN: u64 = 50;
    let backlog: i32 = 0;
    unsafe {
        asm!(
            "syscall",
            in("rax") SYSCALL_LISTEN,
            in("rdi") fd,
            in("rsi") backlog,
        )
    }
}

#[repr(C)]
struct SockaddrIn {
    sin_family: u16,
    sin_port: u16,
    // to listen on all ports, zero this out
    sin_addr: u32,
    sin_zero: [u8; 8],
}

// returns a file descriptor
pub fn tcp_socket() -> i32 {
    const SYSCALL_SOCKET: i32 = 41;
    const SOCK_STREAM: i32 = 1;
    const TYPE: i32 = 0; // not sure if this is right yet
    let mut ret;
    unsafe {
        asm!(
        "syscall",
        inout("rax") SYSCALL_SOCKET => ret,
        in("rdi") ,
        in("rsi") SOCK_STREAM,
        in("rdx") TYPE,
        );
    }
    ret
}

pub fn exit(code: u8) -> ! {
    const SYSCALL_EXIT: u64 = 60;
    unsafe {
        asm!(
            "syscall",
            in("rax") SYSCALL_EXIT,
            in("dil") code,
            options(noreturn)
        )
    }
}

pub fn write(fd: i32, s: &[u8]) {
    const SYSCALL_WRITE: u64 = 1;
    unsafe {
        asm!(
        "syscall",
        in("rax") SYSCALL_WRITE,
        // argument #1
        in("rdi") fd,
        // argument #2
        in("rsi") s.as_ptr() as u64,
        // argument #2
        in("rdx") s.len() as u64,
        )
    }
}

pub const STDOUT: i32 = 1;

matcharoni

from 2021 using Rust

A programming language built around structural pattern matching and parsing. Patterns can capture values, run code, and compose into larger patterns.

Designed and implemented in one week, and placed as a runner-up in langjam 0002.

pat unit {
  n@num ~ 'd' => n * 1440,
  n@num ~ 'h' => n * 60,
  n@num ~ 'm' => n
}
pat minutes ns@[unit]{1+} => sum(ns)
minutes("2h15m")
135
pat bit { '0' => 0, '1' => 1 }
pat bits bs@[bit]{1+} => bs
pat dec bs@bits => sum [*bs << (#bs - %bs - 1) <- bs]
bits("10110")
dec("10110")
[1, 0, 1, 1, 0]
22
// https://adventofcode.com/2021/day/18
pat mag {
  '[' ~ a@mag ~ ',' ~ b@mag ~ ']' =>
    3 * a + (2 * b),
  n@num => n
}
mag("[1,2]")
mag("[[1,2],3]")
7
27

EXAc

from 2021 using Rust

I love this programming game called EXAPUNKS by Zachtronics. But I despised handwriting assembly code, so I made a high level programming language that compiles down to the game's assembly language, and solved all of the puzzles using my language.

xa {
  link 800
  loop {
    spawn { link 2 }
          { link 3 }
          { link 5 }
          { link 7 }
          { link 11 }
          { link 13 }
  }
}
XA
LINK 800
MARK LO_ST_0ZC1H
REPL SP_ST_0_8VRZP
REPL SP_ST_1_8VRZP
REPL SP_ST_2_8VRZP
REPL SP_ST_3_8VRZP
REPL SP_ST_4_8VRZP
REPL SP_ST_5_8VRZP
JUMP SP_EN_8VRZP
MARK SP_ST_0_8VRZP
LINK 2
JUMP SP_EN_8VRZP
MARK SP_ST_1_8VRZP
LINK 3
JUMP SP_EN_8VRZP
MARK SP_ST_2_8VRZP
LINK 5
JUMP SP_EN_8VRZP
MARK SP_ST_3_8VRZP
LINK 7
JUMP SP_EN_8VRZP
MARK SP_ST_4_8VRZP
LINK 11
JUMP SP_EN_8VRZP
MARK SP_ST_5_8VRZP
LINK 13
JUMP SP_EN_8VRZP
MARK SP_EN_8VRZP
JUMP LO_ST_0ZC1H
MARK LO_ED_0ZC1H
EXAPUNKS replay of The Wormhole
spawn create an EXA link move between hosts name/x a name for register X $ch send or receive a message #ctrl a host’s hardware register %repeat repeat code at compile time

Zac

from 2021 using Rust

A programming language where programs can edit their own comments. Designed and implemented in 48 hours, and won🥇in the langjam 0001 competition.

CodeMaestro

from 2018–2020 using Rust and Dear ImGui

CodeMaestro explored programming as direct manipulation of structured code rather than editing plain text.

CodeMaestro stack interpreter showing instruction choices and the result Completed recursive file paths function in CodeMaestro Renaming a Particle field to height updates its uses in the step particle function

golden

from 2018 using Python

Resizes your active window using the golden ratio, an addon for bspwm, a tiling window manager for Linux. Inspired by golden-ratio.el