use std::ffi::CStr;
use crate::{MlxCError, MlxStream, error::check_status, raw};
#[derive(Debug)]
pub struct MlxBindingsContext {
gpu_stream: MlxStream,
version: String,
}
impl MlxBindingsContext {
pub fn new() -> Result<Self, MlxCError> {
let version = read_mlx_version()?;
let gpu_stream = MlxStream::default_gpu()?;
Ok(Self {
gpu_stream,
version,
})
}
pub const fn gpu_stream(&self) -> &MlxStream {
&self.gpu_stream
}
pub fn version(&self) -> &str {
&self.version
}
}
fn read_mlx_version() -> Result<String, MlxCError> {
let raw_version = unsafe { raw::mlx_string_new() };
let mut owned_version = OwnedMlxString(raw_version);
let status = unsafe { raw::mlx_version(&mut owned_version.0) };
check_status(status, "read the linked MLX version")?;
let version_pointer = unsafe { raw::mlx_string_data(owned_version.0) };
if version_pointer.is_null() {
return Err(MlxCError {
operation: "read the linked MLX version",
description: "MLX returned a null version string".to_owned(),
});
}
Ok(unsafe { CStr::from_ptr(version_pointer) }
.to_string_lossy()
.into_owned())
}
struct OwnedMlxString(raw::mlx_string);
impl Drop for OwnedMlxString {
fn drop(&mut self) {
unsafe {
raw::mlx_string_free(self.0);
}
}
}