android_properties/
lib.rs

1//! android-properties is a rust wrapper for bionic property-related syscalls
2
3#![deny(missing_docs, missing_debug_implementations, unused)]
4
5use std::{fmt, os::raw::c_void};
6
7#[cfg(target_os = "android")]
8use crate::android::*;
9#[cfg(not(target_os = "android"))]
10use crate::mock::*;
11
12#[cfg(target_os = "android")]
13/// The implementation of property API for Android bionic-based systems
14pub mod android;
15
16#[cfg(not(target_os = "android"))]
17/// The mock implementation of property API for non-Android based systems
18pub mod mock;
19
20/// A struct representing android properties
21///
22/// This struct consists from a name-value pair
23#[derive(Debug)]
24pub struct AndroidProperty {
25    /// Property name
26    name: String,
27    /// Property info pointer
28    property_info: *const c_void,
29}
30
31impl AndroidProperty {
32    /// Initializes and returns struct representing android properties
33    pub fn new(name: &str) -> Self {
34        AndroidProperty {
35            name: name.to_string(),
36            property_info: std::ptr::null(),
37        }
38    }
39
40    /// Return property name
41    pub fn name(&self) -> String {
42        self.name.clone()
43    }
44
45    /// Return property value
46    pub fn value(&mut self) -> Option<String> {
47        if self.property_info.is_null() {
48            self.property_info = plat_get_property_info(&self.name);
49        }
50        plat_getprop(&self.name, self.property_info)
51    }
52
53    /// Set property value
54    pub fn set_value(&self, value: &str) -> Result<(), String> {
55        plat_setprop(&self.name, value)
56    }
57}
58
59impl fmt::Display for AndroidProperty {
60    // Output in format [<name>]: [<value>]
61    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62        let mut property_info = self.property_info;
63        if property_info.is_null() {
64            property_info = plat_get_property_info(&self.name);
65        }
66        write!(
67            f,
68            "[{}]: [{}]",
69            self.name,
70            plat_getprop(&self.name, property_info).unwrap_or_else(|| "".into())
71        )
72    }
73}
74
75/// Returns the property value if it exists
76pub fn getprop(name: &str) -> AndroidProperty {
77    AndroidProperty::new(name)
78}
79
80/// Sets the property value if it exists or creates new one with specified value
81pub fn setprop(name: &str, value: &str) -> Result<(), String> {
82    AndroidProperty::new(name).set_value(value)
83}
84
85/// Returns an iterator to vector, which contains all properties present in a system
86pub fn prop_values() -> impl Iterator<Item = AndroidProperty> {
87    #[cfg(target_os = "android")]
88    return crate::android::plat_prop_values();
89
90    #[cfg(not(target_os = "android"))]
91    return crate::mock::plat_prop_values();
92}