corevm-guest 0.1.28

API/SDK for CoreVM guest programs
Documentation
//! Rust wrappers around C API.

#![allow(clippy::missing_safety_doc)]

use crate::c;
use core::mem::size_of_val;
use corevm_types::{AudioMode, VideoFrameFormat, VideoMode};

/// Get the current amount of gas.
#[inline]
pub fn gas() -> u64 {
	unsafe { c::gas() }
}

/// Allocate memory block of the specified size.
///
/// - The size is rounded up to the next multiple of page size.
/// - The returned address is aligned at a page boundary.
///
/// Returns the pointer to the allocated memory region or [`null_mut()`](core::ptr::null_mut) if the
/// allocation was unsuccessful.
#[inline]
pub unsafe fn alloc(size: u64) -> *mut u8 {
	c::alloc(size) as *mut u8
}

/// Deallocate the memory block of the specified size starting at `address`.
///
/// Deallocates *all* the pages that overlap the memory block.
#[inline]
pub unsafe fn free(address: *mut u8, size: u64) {
	c::free(address as u64, size)
}

/// Console stream type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConsoleStream {
	/// Standard output stream.
	Stdout = 1,
	/// Standard error stream.
	Stderr = 2,
}

/// Append `data` to the specified _console_ output stream.
#[inline]
pub fn yield_console_data<S: AsRef<[u8]>>(stream: ConsoleStream, data: S) {
	let bytes = data.as_ref();
	let len = bytes.len() as u64;
	unsafe { c::yield_console_data(stream as u64, bytes.as_ptr() as u64, len) };
}

/// Append video frame to the _video_ output stream.
#[inline]
pub fn yield_video_frame(frame: &[u8], format: VideoFrameFormat) {
	let address = frame.as_ptr() as u64;
	let len = size_of_val(frame) as u64;
	unsafe { c::yield_video_frame(address, len, format as u64) };
}

/// Set video monitor output mode to `mode`.
#[inline]
pub fn video_mode(mode: VideoMode) {
	unsafe {
		c::video_mode(
			u64::from(mode.width.get()),
			u64::from(mode.height.get()),
			u64::from(mode.refresh_rate.get()),
			mode.options.as_u64(),
		)
	}
}

/// Append audio samples to the _audio_ output stream.
///
/// Sample format is defined by [`audio_mode`](crate::audio_mode).
#[inline]
pub fn yield_audio_samples<T: AudioSample>(samples: &[T]) {
	let address = samples.as_ptr() as u64;
	let len = size_of_val(samples) as u64;
	unsafe { c::yield_audio_samples(address, len) };
}

/// Marker trait for types that can be used as audio samples.
pub trait AudioSample: Copy + Sized {}

impl AudioSample for u8 {}
impl AudioSample for i16 {}

/// Set audio output mode to `mode`.
#[inline]
pub fn audio_mode(mode: AudioMode) {
	unsafe {
		c::audio_mode(
			u64::from(mode.channels.get()),
			u64::from(mode.sample_rate.get()),
			mode.sample_format as u64,
		)
	}
}