libmpv_client/types/
byte_array.rs

1use std::ffi::c_void;
2use std::marker::PhantomData;
3use std::mem::MaybeUninit;
4use libmpv_client_sys::mpv_byte_array;
5use crate::*;
6use crate::types::traits::{MpvFormat, MpvRecv, MpvRecvInternal, MpvRepr, MpvSend, MpvSendInternal, ToMpvRepr};
7
8/// A [`Vec<u8>`] representing a raw, untyped byte array. Only used with [`Node`], and only in some very specific situations. (Some commands use it.)
9pub type ByteArray = Vec<u8>;
10
11#[derive(Debug)]
12pub(crate) struct MpvByteArray<'a> {
13    _original: PhantomData<&'a ByteArray>,
14
15    byte_array: Box<mpv_byte_array>
16}
17
18impl MpvRepr for MpvByteArray<'_> {
19    type Repr = mpv_byte_array;
20
21    fn ptr(&self) -> *const Self::Repr {
22        &raw const *self.byte_array
23    }
24}
25
26impl MpvFormat for ByteArray {
27    const MPV_FORMAT: Format = Format::BYTE_ARRAY;
28}
29
30impl From<ByteArray> for Node {
31    fn from(value: ByteArray) -> Self {
32        Node::ByteArray(value)
33    }
34}
35
36impl From<&ByteArray> for Node {
37    fn from(value: &ByteArray) -> Self {
38        Node::ByteArray(value.clone())
39    }
40}
41
42impl MpvRecv for ByteArray {}
43impl MpvRecvInternal for ByteArray {
44    unsafe fn from_ptr(ptr: *const c_void) -> Result<Self> {
45        check_null!(ptr);
46        let byte_array = unsafe { *(ptr as *const mpv_byte_array) };
47
48        check_null!(byte_array.data);
49        Ok(unsafe { std::slice::from_raw_parts(byte_array.data as *const u8, byte_array.size) }.to_vec())
50    }
51
52    unsafe fn from_mpv<F: Fn(*mut c_void) -> Result<i32>>(fun: F) -> Result<Self> {
53        let mut ba: MaybeUninit<mpv_byte_array> = MaybeUninit::uninit();
54
55        fun(ba.as_mut_ptr() as *mut c_void).map(|_| {
56            unsafe { Self::from_ptr(ba.as_ptr() as *const c_void) }
57        })?
58    }
59}
60
61impl MpvSend for ByteArray {}
62impl MpvSendInternal for ByteArray {
63    fn to_mpv<F: Fn(*mut c_void) -> Result<i32>>(&self, fun: F) -> Result<i32> {
64        let repr = self.to_mpv_repr();
65
66        fun(repr.ptr() as *mut c_void)
67    }
68}
69
70impl ToMpvRepr for ByteArray {
71    type ReprWrap<'a> = MpvByteArray<'a>;
72
73    fn to_mpv_repr(&self) -> Self::ReprWrap<'_> {
74        MpvByteArray {
75            _original: PhantomData,
76            byte_array: Box::new(mpv_byte_array {
77                data: self.as_ptr() as *mut c_void,
78                size: self.len(),
79            }),
80        }
81    }
82}