1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
use spa::prelude::*;
use std::{ffi::CString, fmt, mem::ManuallyDrop, ptr};
/// A collection of key/value pairs.
///
/// # Examples
/// Create a `Properties` struct and access the stored values by key:
/// ```rust
/// use pipewire::{prelude::*, properties::{properties, Properties}};
///
/// let props = properties!{
/// "Key" => "Value",
/// "OtherKey" => "OtherValue"
/// };
///
/// assert_eq!(Some("Value"), props.get("Key"));
/// assert_eq!(Some("OtherValue"), props.get("OtherKey"));
/// ```
pub struct Properties {
ptr: ptr::NonNull<pw_sys::pw_properties>,
}
/// A macro for creating a new `Properties` struct with predefined key-value pairs.
///
/// The macro accepts a list of `Key => Value` pairs, separated by commas.
///
/// # Examples:
/// Create a `Properties` struct from literals.
/// ```rust
/// use pipewire::properties::properties;
///
/// let props = properties!{
/// "Key1" => "Value1",
/// "Key2" => "Value2",
/// };
/// ```
///
/// Any expression that evaluates to a `impl Into<Vec<u8>>` can be used for both keys and values.
/// ```rust
/// use pipewire::prelude::*;
/// use pipewire::properties::properties;
///
/// let key = String::from("Key");
/// let value = vec![86, 97, 108, 117, 101]; // "Value" as an ASCII u8 vector.
/// let props = properties!{
/// key => value
/// };
///
/// assert_eq!(Some("Value"), props.get("Key"));
/// ```
#[macro_export]
macro_rules! __properties__ {
{$($k:expr => $v:expr),+ $(,)?} => {{
let mut properties = $crate::properties::Properties::new();
$(
<$crate::properties::Properties as $crate::spa::utils::dict::WritableDict>::insert(&mut properties, $k, $v);
)*
properties
}};
}
pub use __properties__ as properties;
impl Properties {
/// Create a new, initially empty `Properties` struct.
pub fn new() -> Self {
unsafe {
let raw = std::ptr::NonNull::new(pw_sys::pw_properties_new(std::ptr::null()))
.expect("Newly created pw_properties should not be null");
Self::from_ptr(raw)
}
}
/// Create a `Properties` struct from an existing raw `pw_properties` pointer.
///
/// # Safety
/// - The provided pointer must point to a valid, well-aligned `pw_properties` struct.
/// - After this call, the generated `Properties` struct will assume ownership of the data pointed to,
/// so that data must not be freed elsewhere.
pub unsafe fn from_ptr(ptr: ptr::NonNull<pw_sys::pw_properties>) -> Self {
Self { ptr }
}
/// Consume the `Properties` struct, returning a pointer to the raw `pw_properties` struct.
///
/// After this function, the caller is responsible for `pw_properties` struct,
/// and should make sure it is freed when it is no longer needed.
pub fn into_raw(self) -> *mut pw_sys::pw_properties {
let this = ManuallyDrop::new(self);
this.ptr.as_ptr()
}
// TODO: `fn from_string` that calls `pw_sys::pw_properties_new_string`
// TODO: bindings for pw_properties_update_keys, pw_properties_update, pw_properties_add, pw_properties_add_keys
/// Create a new `Properties` from a given dictionary.
///
/// All the keys and values from `dict` are copied.
pub fn from_dict<D: ReadableDict>(dict: &D) -> Self {
let ptr = dict.get_dict_ptr();
unsafe {
let copy = pw_sys::pw_properties_new_dict(ptr);
Self::from_ptr(ptr::NonNull::new(copy).expect("pw_properties_new_dict() returned NULL"))
}
}
}
impl ReadableDict for Properties {
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict {
self.as_raw_ptr().cast()
}
}
impl WritableDict for Properties {
fn insert<K: Into<Vec<u8>>, V: Into<Vec<u8>>>(&mut self, key: K, value: V) {
let k = CString::new(key).unwrap();
let v = CString::new(value).unwrap();
unsafe { pw_sys::pw_properties_set(self.as_raw_ptr(), k.as_ptr(), v.as_ptr()) };
}
fn remove<K: Into<Vec<u8>>>(&mut self, key: K) {
let key = CString::new(key).unwrap();
unsafe { pw_sys::pw_properties_set(self.as_raw_ptr(), key.as_ptr(), std::ptr::null()) };
}
fn clear(&mut self) {
unsafe { pw_sys::pw_properties_clear(self.as_raw_ptr()) }
}
}
impl Default for Properties {
fn default() -> Self {
Self::new()
}
}
impl Clone for Properties {
fn clone(&self) -> Self {
unsafe {
let ptr = pw_sys::pw_properties_copy(self.as_raw_ptr());
let ptr = ptr::NonNull::new_unchecked(ptr);
Self { ptr }
}
}
}
impl std::ops::Deref for Properties {
type Target = PropertiesRef;
fn deref(&self) -> &Self::Target {
unsafe { self.ptr.cast().as_ref() }
}
}
impl std::ops::DerefMut for Properties {
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.ptr.cast().as_mut() }
}
}
impl Drop for Properties {
fn drop(&mut self) {
unsafe { pw_sys::pw_properties_free(self.ptr.as_ptr()) }
}
}
impl fmt::Debug for Properties {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.debug("Properties", f)
}
}
#[repr(transparent)]
pub struct PropertiesRef(pw_sys::pw_properties);
impl PropertiesRef {
pub fn as_raw(&self) -> &pw_sys::pw_properties {
&self.0
}
/// Obtain a pointer to the underlying `pw_properties` struct.
///
/// The pointer is only valid for the lifetime of the [`PropertiesRef`] struct the pointer was obtained from,
/// and must not be dereferenced after it is dropped.
///
/// Ownership of the `pw_properties` struct is not transferred to the caller and must not be manually freed.
pub fn as_raw_ptr(&self) -> *mut pw_sys::pw_properties {
std::ptr::addr_of!(self.0).cast_mut()
}
pub fn to_owned(&self) -> Properties {
unsafe {
let ptr = pw_sys::pw_properties_copy(self.as_raw_ptr());
Properties::from_ptr(ptr::NonNull::new_unchecked(ptr))
}
}
}
impl ReadableDict for PropertiesRef {
fn get_dict_ptr(&self) -> *const spa_sys::spa_dict {
self.as_raw_ptr().cast()
}
}
impl WritableDict for PropertiesRef {
fn insert<K: Into<Vec<u8>>, V: Into<Vec<u8>>>(&mut self, key: K, value: V) {
let k = CString::new(key).unwrap();
let v = CString::new(value).unwrap();
unsafe { pw_sys::pw_properties_set(self.as_raw_ptr(), k.as_ptr(), v.as_ptr()) };
}
fn remove<K: Into<Vec<u8>>>(&mut self, key: K) {
let key = CString::new(key).unwrap();
unsafe { pw_sys::pw_properties_set(self.as_raw_ptr(), key.as_ptr(), std::ptr::null()) };
}
fn clear(&mut self) {
unsafe { pw_sys::pw_properties_clear(self.as_raw_ptr()) }
}
}
impl fmt::Debug for PropertiesRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.debug("PropertiesRef", f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new() {
let props = properties! {
"K0" => "V0"
};
let mut iter = props.iter();
assert_eq!(("K0", "V0"), iter.next().unwrap());
assert_eq!(None, iter.next());
}
#[test]
fn remove() {
let mut props = properties! {
"K0" => "V0"
};
assert_eq!(Some("V0"), props.get("K0"));
props.remove("K0");
assert_eq!(None, props.get("K0"));
}
#[test]
fn insert() {
let mut props = properties! {
"K0" => "V0"
};
assert_eq!(None, props.get("K1"));
props.insert("K1", "V1");
assert_eq!(Some("V1"), props.get("K1"));
}
#[test]
fn clone() {
let props1 = properties! {
"K0" => "V0"
};
let mut props2 = props1.clone();
props2.insert("K1", "V1");
// Now, props2 should contain ("K1", "V1"), but props1 should not.
assert_eq!(None, props1.get("K1"));
assert_eq!(Some("V1"), props2.get("K1"));
}
#[test]
fn from_dict() {
use spa::static_dict;
let mut props = {
let dict = static_dict! { "K0" => "V0" };
Properties::from_dict(&dict)
};
assert_eq!(props.len(), 1);
assert_eq!(props.get("K0"), Some("V0"));
props.insert("K1", "V1");
assert_eq!(props.len(), 2);
assert_eq!(props.get("K1"), Some("V1"));
}
}