keebrs 0.3.0

Keyboard firmware building blocks
use core::{
    pin::Pin,
    task::{
        Context,
        Poll,
    },
};

use super::*;

use embrio_core::io::{
    Cursor,
    Read,
    Write,
};

use futures::{
    prelude::*,
    task::noop_waker,
};

use crate::key::*;

fn block_on<F>(mut f: F) -> F::Output
where
    F: Future,
{
    unsafe {
        let mut pinned = Pin::new_unchecked(&mut f);
        loop {
            match pinned
                .as_mut()
                .poll(&mut Context::from_waker(&noop_waker()))
            {
                Poll::Ready(v) => return v,
                _ => continue,
            }
        }
    }
}

fn _is_write<W: Write>(_w: &W) {}
fn _is_read<R: Read>(_r: &R) {}
fn _is_mut_u8<W: AsMut<[u8]>>(_w: &W) {}

#[test]
fn key_chan() {
    use super::super::codec::PostCardCodec;
    let mut buf = vec![0u8; 64];

    _is_mut_u8(&buf);

    let writer = Cursor::new(&mut buf);

    _is_write(&writer);

    let mut sink = PostCardCodec::<Msg>::sink::<_, [u8; 32]>(writer);

    let keys = vec![
        Msg::KeyEvent(PhysKey {
            pos: KeyPos { x: 1, y: 2 },
            state: true.into(),
        }),
        Msg::KeyEvent(PhysKey {
            pos: KeyPos { x: 1, y: 2 },
            state: false.into(),
        }),
        Msg::KeyEvent(PhysKey {
            pos: KeyPos { x: 4, y: 0 },
            state: true.into(),
        }),
        Msg::KeyEvent(PhysKey {
            pos: KeyPos { x: 4, y: 0 },
            state: false.into(),
        }),
    ];

    for key in &keys {
        block_on(sink.send(key.clone())).unwrap();
    }

    drop(sink);

    let reader = &*buf;

    _is_read(&reader);

    let mut stream = PostCardCodec::<Msg>::stream::<_, [u8; 32]>(reader);

    let mut output = vec![];
    for _ in 0..keys.len() {
        output.push(block_on(stream.try_next()).unwrap().unwrap());
    }
    dbg!(&keys);
    dbg!(&output);
    assert_eq!(keys, output);
}

#[test]
fn test_postcard() {
    use crate::key::*;
    let mut buf = [0u8; 32];
    let key = PhysKey {
        pos: KeyPos { x: 2, y: 4 },
        state: true.into(),
    };

    let data = postcard::to_slice_cobs(&Msg::KeyEvent(key), &mut buf[..]).unwrap();

    dbg!(data);
}