vtx-sdk 0.1.14

Official SDK for developing VTX plugins using Rust and WebAssembly.
Documentation
//! Host-side VFS helpers.

use crate::bindings::vtx::api::vtx_vfs::{self, Buffer, VtxObjectMeta};
use crate::error::{VtxError, VtxResult};
use serde::de::DeserializeOwned;
use serde::Serialize;

use super::stream::BufferExt;

/// VFS buffer handle type alias.
pub type VfsBuffer = Buffer;

/// VFS object metadata type alias.
pub type VfsObjectMeta = VtxObjectMeta;

/// Opens a VFS URI and returns a `Buffer` resource handle.
pub fn open_uri(uri: &str) -> VtxResult<Buffer> {
    vtx_vfs::open_uri(uri).map_err(VtxError::from_host_message)
}

/// Creates an in-memory buffer (typically used for constructing response bodies).
pub fn create_memory_buffer(data: impl AsRef<[u8]>) -> Buffer {
    vtx_vfs::create_memory_buffer(data.as_ref())
}

/// Creates an in-memory UTF-8 buffer.
pub fn buffer_from_string(data: &str) -> Buffer {
    create_memory_buffer(data.as_bytes())
}

/// Creates an in-memory JSON buffer.
pub fn buffer_from_json<T: Serialize>(data: &T) -> VtxResult<Buffer> {
    let bytes =
        serde_json::to_vec(data).map_err(|e| VtxError::SerializationError(e.to_string()))?;
    Ok(create_memory_buffer(bytes))
}

/// Reads metadata for a single VFS object.
pub fn head(uri: &str) -> VtxResult<VtxObjectMeta> {
    vtx_vfs::head(uri).map_err(VtxError::from_host_message)
}

/// Lists objects under a prefix URI.
pub fn list_objects(prefix_uri: &str) -> VtxResult<Vec<VtxObjectMeta>> {
    vtx_vfs::list_objects(prefix_uri).map_err(VtxError::from_host_message)
}

/// Reads a byte range from a VFS object.
pub fn read_range(uri: &str, offset: u64, len: u64) -> VtxResult<Vec<u8>> {
    vtx_vfs::read_range(uri, offset, len).map_err(VtxError::from_host_message)
}

/// Reads all bytes from a VFS URI.
pub fn read_all(uri: &str) -> VtxResult<Vec<u8>> {
    let buffer = open_uri(uri)?;
    Ok(buffer.read_all())
}

/// Reads all bytes from a VFS URI and decodes as UTF-8.
pub fn read_to_string(uri: &str) -> VtxResult<String> {
    let buffer = open_uri(uri)?;
    buffer.read_to_string()
}

/// Reads a VFS URI and deserializes JSON into the target type.
pub fn read_json<T: DeserializeOwned>(uri: &str) -> VtxResult<T> {
    let buffer = open_uri(uri)?;
    buffer.read_json()
}