Skip to main content

corevm_guest/
rust.rs

1//! Rust wrappers around C API.
2
3#![allow(clippy::missing_safety_doc)]
4
5use crate::c;
6use core::mem::size_of_val;
7use corevm_types::{AudioMode, VideoFrameFormat, VideoMode};
8
9/// Get the current amount of gas.
10#[inline]
11pub fn gas() -> u64 {
12	unsafe { c::gas() }
13}
14
15/// Allocate memory block of the specified size.
16///
17/// - The size is rounded up to the next multiple of page size.
18/// - The returned address is aligned at a page boundary.
19///
20/// Returns the pointer to the allocated memory region or [`null_mut()`](core::ptr::null_mut) if the
21/// allocation was unsuccessful.
22#[inline]
23pub unsafe fn alloc(size: u64) -> *mut u8 {
24	c::alloc(size) as *mut u8
25}
26
27/// Deallocate the memory block of the specified size starting at `address`.
28///
29/// Deallocates *all* the pages that overlap the memory block.
30#[inline]
31pub unsafe fn free(address: *mut u8, size: u64) {
32	c::free(address as u64, size)
33}
34
35/// Console stream type.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ConsoleStream {
38	/// Standard output stream.
39	Stdout = 1,
40	/// Standard error stream.
41	Stderr = 2,
42}
43
44/// Append `data` to the specified _console_ output stream.
45#[inline]
46pub fn yield_console_data<S: AsRef<[u8]>>(stream: ConsoleStream, data: S) {
47	let bytes = data.as_ref();
48	let len = bytes.len() as u64;
49	unsafe { c::yield_console_data(stream as u64, bytes.as_ptr() as u64, len) };
50}
51
52/// Append video frame to the _video_ output stream.
53#[inline]
54pub fn yield_video_frame(frame: &[u8], format: VideoFrameFormat) {
55	let address = frame.as_ptr() as u64;
56	let len = size_of_val(frame) as u64;
57	unsafe { c::yield_video_frame(address, len, format as u64) };
58}
59
60/// Set video monitor output mode to `mode`.
61#[inline]
62pub fn video_mode(mode: VideoMode) {
63	unsafe {
64		c::video_mode(
65			u64::from(mode.width.get()),
66			u64::from(mode.height.get()),
67			u64::from(mode.refresh_rate.get()),
68			mode.options.as_u64(),
69		)
70	}
71}
72
73/// Append audio samples to the _audio_ output stream.
74///
75/// Sample format is defined by [`audio_mode`](crate::audio_mode).
76#[inline]
77pub fn yield_audio_samples<T: AudioSample>(samples: &[T]) {
78	let address = samples.as_ptr() as u64;
79	let len = size_of_val(samples) as u64;
80	unsafe { c::yield_audio_samples(address, len) };
81}
82
83/// Marker trait for types that can be used as audio samples.
84pub trait AudioSample: Copy + Sized {}
85
86impl AudioSample for u8 {}
87impl AudioSample for i16 {}
88
89/// Set audio output mode to `mode`.
90#[inline]
91pub fn audio_mode(mode: AudioMode) {
92	unsafe {
93		c::audio_mode(
94			u64::from(mode.channels.get()),
95			u64::from(mode.sample_rate.get()),
96			mode.sample_format as u64,
97		)
98	}
99}