Writers for the web

I made some "writers" for my game to put ouput to the webpage, but not on in my egui-canvas.

For a popup alert and console. Pretty plain. There is some web_sys and js_sys calls. Am I doing this correctly. The alert was simple.

pub mod alert {

    pub struct Alert {}

    impl std::io::Write for Alert {
        fn write(&mut self, buffer: &[u8]) -> Result<usize, std::io::Error> {
            if let Some(window) = web_sys::window() {
                if let Ok(msg) = std::str::from_utf8(buffer) {
                    let _ = window.alert_with_message(msg);
                }
            }
            Ok(buffer.len())
        }
        fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
            Ok(())
        }
    }
}

This works with no issues, that I can find. My calling code sends in a String.as_bytes()
The console version was a bit harder.

pub mod console {

    pub struct Console {}

    impl std::io::Write for Console {
        fn write(&mut self, buffer: &[u8]) -> Result<usize, std::io::Error> {
            if let Ok(msg) = std::str::from_utf8(buffer) {
                let msg = js_sys::JsString::from(msg);
                let ar = js_sys::Array::new();
                ar.push(&msg);
                web_sys::console::log(&ar);
            }
            Ok(buffer.len())
        }
        fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
            Ok(())
        }
    }
}

I was using the line

web_sys::console::log(&js_sys::Array::from(msg));

This gave me WAT. Spaces between each character.. One day at my $real job$ I was under a sink and I thought, DUH. It made an Array from the Strings parts. Not an Array with the String as an element.

Anyway, thanks for looking and telling me whats wrong.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.