Explain runtime invariants and avoid redundant unwraps

This commit is contained in:
Samuel Onoja committed 2026-10-22 01:28:03 +01:00
1 parent 34f2f07301
commit 1b51ba83b4
116 files changed
+1643 -515

No files matched your search

+22 -5
View File
@@ -210,7 +210,11 @@ pub(crate) async fn authorize(
.ok_or_else(|| zbus::fdo::Error::AccessDenied("Missing caller".into()))?;
let dbus = zbus::fdo::DBusProxy::new(connection).await?;
let owner = dbus
.get_name_owner(FRONTEND.try_into().unwrap())
.get_name_owner(
FRONTEND
.try_into()
.expect("the portal frontend has a valid static bus name"),
)
.await
.map_err(|_| zbus::fdo::Error::AccessDenied("Desktop portal is unavailable".into()))?;
if sender.as_str() != owner.as_str() {
@@ -608,9 +612,15 @@ async fn picker(prompt: &Prompt) -> Result<Child, String> {
.kill_on_drop(true)
.spawn()
.map_err(|e| e.to_string())?;
let mut input = child.stdin.take().unwrap();
let mut input = child
.stdin
.take()
.expect("the child was spawned with piped standard input");
input
.write_all(&serde_json::to_vec(prompt).unwrap())
.write_all(
&serde_json::to_vec(prompt)
.expect("typed configuration and IPC values must serialize to JSON"),
)
.await
.map_err(|e| e.to_string())?;
drop(input);
@@ -855,7 +865,10 @@ async fn start_streams(
.spawn()
.map_err(|e| e.to_string())?;
let mut line = String::new();
let output = child.stdout.take().unwrap();
let output = child
.stdout
.take()
.expect("the child was spawned with piped standard output");
tokio::time::timeout(
Duration::from_secs(10),
BufReader::new(output).read_line(&mut line),
@@ -1129,7 +1142,11 @@ pub async fn run() -> Result<(), Box<dyn std::error::Error>> {
tokio::time::sleep(Duration::from_secs(1)).await;
let owner = match zbus::fdo::DBusProxy::new(&connection).await {
Ok(proxy) => proxy
.get_name_owner(FRONTEND.try_into().unwrap())
.get_name_owner(
FRONTEND
.try_into()
.expect("the portal frontend has a valid static bus name"),
)
.await
.ok()
.map(|name| name.to_string()),
+4 -1
View File
@@ -234,7 +234,10 @@ impl Capture {
}
frame.destroy();
self.state.result.take().unwrap()?;
self.state
.result
.take()
.expect("the capture dispatch loop exits after storing its result")?;
let buffer = self
.state
+5 -1
View File
@@ -163,7 +163,11 @@ impl cosmic::Application for Consent {
if self.prompt.shortcuts.is_empty() {
println!("true");
} else {
println!("{}", serde_json::to_string(&self.prompt.shortcuts).unwrap());
println!(
"{}",
serde_json::to_string(&self.prompt.shortcuts)
.expect("typed configuration and IPC values must serialize to JSON")
);
}
let _ = std::io::stdout().flush();
return cosmic::iced::exit();
+8 -2
View File
@@ -229,7 +229,10 @@ pub(crate) async fn consent(
.spawn()
.map_err(|error| error.to_string())?;
let pid = child.id().ok_or("Missing consent process ID")?;
let mut input = child.stdin.take().unwrap();
let mut input = child
.stdin
.take()
.expect("the child was spawned with piped standard input");
input
.write_all(&serde_json::to_vec(&prompt).map_err(|error| error.to_string())?)
@@ -578,7 +581,10 @@ async fn select_window(app: &str, parent: &str) -> Result<Option<u64>, String> {
.spawn()
.map_err(|error| error.to_string())?;
let pid = child.id().ok_or("Missing window selector PID")?;
let mut stdin = child.stdin.take().unwrap();
let mut stdin = child
.stdin
.take()
.expect("the child was spawned with piped standard input");
stdin
.write_all(&serde_json::to_vec(&prompt).map_err(|error| error.to_string())?)
.await
+5 -3
View File
@@ -157,17 +157,19 @@ impl Inhibit {
let values = HashMap::from([
(
"screensaver-active".into(),
Value::from(locked).try_into().unwrap(),
Value::from(locked).try_into().expect("the D-Bus value uses an owned supported scalar or collection type"),
),
(
"session-state".into(),
Value::from(phase).try_into().unwrap(),
Value::from(phase).try_into().expect("the D-Bus value uses an owned supported scalar or collection type"),
),
]);
if let Ok(emitter) = SignalEmitter::new(&connection, PATH)
&& Self::state_changed(
&emitter,
OwnedObjectPath::try_from(path.clone()).unwrap(),
OwnedObjectPath::try_from(path.clone()).expect(
"session handles were validated as D-Bus object paths",
),
values,
)
.await
+12 -2
View File
@@ -506,7 +506,12 @@ impl InputCapture {
return Ok((1, Options::new()));
}
let result = self
.finish_native_call(connection, &session_handle, &bridge, result.unwrap())
.finish_native_call(
connection,
&session_handle,
&bridge,
result.expect("the completion loop returned with a native call result"),
)
.await?;
let zones: Vec<(u32, u32, i32, i32)> = serde_json::from_value(result["zones"].clone())
.map_err(|_| invalid("Invalid native capture zones"))?;
@@ -582,7 +587,12 @@ impl InputCapture {
return Ok((1, Options::new()));
}
let result = self
.finish_native_call(connection, &session_handle, &bridge, result.unwrap())
.finish_native_call(
connection,
&session_handle,
&bridge,
result.expect("the completion loop returned with a native call result"),
)
.await?;
let failed_barriers: Vec<u32> = serde_json::from_value(result["failed_barriers"].clone())
.map_err(|_| invalid("Invalid native barrier response"))?;
+5 -2
View File
@@ -31,7 +31,8 @@ impl Lockdown {
}
pub(crate) async fn watch(self, connection: Connection) {
let emitter = SignalEmitter::new(&connection, PATH).unwrap();
let emitter = SignalEmitter::new(&connection, PATH)
.expect("the portal exports signals at a valid static object path");
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
let mut current = self.0.write().await;
@@ -49,7 +50,9 @@ impl Lockdown {
drop(current);
let _ = zbus::fdo::Properties::properties_changed(
&emitter,
"org.freedesktop.impl.portal.Lockdown".try_into().unwrap(),
"org.freedesktop.impl.portal.Lockdown"
.try_into()
.expect("the Lockdown interface has a valid static D-Bus name"),
changed,
Cow::Borrowed(&[]),
)
+2 -1
View File
@@ -150,7 +150,8 @@ impl Background {
}
pub(crate) async fn watch(self, connection: Connection) {
let emitter = SignalEmitter::new(&connection, PATH).unwrap();
let emitter = SignalEmitter::new(&connection, PATH)
.expect("the portal exports signals at a valid static object path");
loop {
let result = async {
let path = ferese_ipc::socket::resolve(None).map_err(|error| error.to_string())?;
+10 -2
View File
@@ -250,7 +250,11 @@ impl cosmic::Application for Picker {
.map(|i| &self.prompt.sources[*i].name)
.collect();
if self.prompt.window_capture {
println!("{}", serde_json::to_string(&names).unwrap());
println!(
"{}",
serde_json::to_string(&names)
.expect("typed configuration and IPC values must serialize to JSON")
);
} else {
let selection = Selection {
names: names.into_iter().cloned().collect(),
@@ -262,7 +266,11 @@ impl cosmic::Application for Picker {
audio: self.audio,
region: self.region,
};
println!("{}", serde_json::to_string(&selection).unwrap());
println!(
"{}",
serde_json::to_string(&selection)
.expect("typed configuration and IPC values must serialize to JSON")
);
}
let _ = std::io::stdout().flush();
return cosmic::iced::exit();
+2 -1
View File
@@ -28,7 +28,8 @@ pub fn event(state: &str, message: Option<&str>, path: Option<&Path>) {
}
fn option_string(value: String) -> OwnedValue {
OwnedValue::try_from(Value::from(value)).unwrap()
OwnedValue::try_from(Value::from(value))
.expect("the D-Bus value uses an owned supported scalar or collection type")
}
async fn request<B: serde::Serialize + zbus::zvariant::DynamicType>(
+5 -2
View File
@@ -44,7 +44,9 @@ impl Appearance {
("color-scheme".into(), self.scheme.into()),
(
"accent-color".into(),
Value::from(self.accent).try_to_owned().unwrap(),
Value::from(self.accent)
.try_to_owned()
.expect("the D-Bus value uses an owned supported scalar or collection type"),
),
("contrast".into(), self.contrast.into()),
("reduced-motion".into(), self.reduced_motion.into()),
@@ -83,7 +85,8 @@ impl Settings {
}
pub(crate) async fn watch(self, connection: Connection) {
let emitter = SignalEmitter::new(&connection, PATH).unwrap();
let emitter = SignalEmitter::new(&connection, PATH)
.expect("the portal exports signals at a valid static object path");
loop {
let connection = tokio::task::spawn_blocking(ferese_ipc::Connection::connect).await;
if let Ok(Ok(mut connection)) = connection
+20 -6
View File
@@ -210,7 +210,8 @@ impl GlobalShortcuts {
session: Arc<Session>,
bridge: Bridge,
) {
let emitter = SignalEmitter::new(&connection, PATH).unwrap();
let emitter = SignalEmitter::new(&connection, PATH)
.expect("the portal exports signals at a valid static object path");
loop {
tokio::select! {
_ = session.cancel.wait() => break,
@@ -414,7 +415,12 @@ impl GlobalShortcuts {
self.requests.end(connection, &handle).await;
Ok((
0,
HashMap::from([("shortcuts".into(), Value::from(result).try_into().unwrap())]),
HashMap::from([(
"shortcuts".into(),
Value::from(result)
.try_into()
.expect("the D-Bus value uses an owned supported scalar or collection type"),
)]),
))
}
@@ -453,7 +459,8 @@ impl GlobalShortcuts {
.await;
session.state.lock().await.busy = false;
if let Ok(Some(shortcuts)) = result {
let emitter = SignalEmitter::new(&connection, PATH).unwrap();
let emitter = SignalEmitter::new(&connection, PATH)
.expect("the portal exports signals at a valid static object path");
let _ = Self::shortcuts_changed(&emitter, session_handle, shortcuts).await;
}
});
@@ -597,7 +604,9 @@ fn reply(response: Result<Option<Shortcuts>, String>) -> (u32, Options) {
0,
HashMap::from([(
"shortcuts".into(),
Value::from(shortcuts).try_into().unwrap(),
Value::from(shortcuts)
.try_into()
.expect("the D-Bus value uses an owned supported scalar or collection type"),
)]),
),
Ok(None) => (1, Options::new()),
@@ -629,7 +638,10 @@ async fn dialog(
.stderr(Stdio::inherit())
.spawn()
.map_err(|error| error.to_string())?;
let mut input = child.stdin.take().unwrap();
let mut input = child
.stdin
.take()
.expect("the child was spawned with piped standard input");
input
.write_all(&serde_json::to_vec(&prompt).map_err(|error| error.to_string())?)
.await
@@ -705,7 +717,9 @@ fn save(app: &str, fields: &[ShortcutField]) -> Result<(), String> {
let Some(path) = cache_path(app) else {
return Ok(());
};
let directory = path.parent().unwrap();
let directory = path
.parent()
.expect("the portal configuration path identifies a file in a directory");
std::fs::create_dir_all(directory).map_err(|error| error.to_string())?;
let mut file = tempfile::NamedTempFile::new_in(directory).map_err(|error| error.to_string())?;
std::io::Write::write_all(
+18 -9
View File
@@ -106,7 +106,7 @@ fn pod(object: spa::pod::Object) -> Vec<u8> {
std::io::Cursor::new(Vec::new()),
&spa::pod::Value::Object(object),
)
.unwrap()
.expect("SPA pod serialization into an owned Vec cannot fail for these object types")
.0
.into_inner()
}
@@ -230,7 +230,7 @@ pub fn run(
width,
height
})
.unwrap()
.expect("typed configuration and IPC values must serialize to JSON")
);
let _ = std::io::stdout().flush();
}
@@ -291,8 +291,10 @@ pub fn run(
));
if stream
.update_params(&mut [
Pod::from_bytes(&buffers).unwrap(),
Pod::from_bytes(&header).unwrap(),
Pod::from_bytes(&buffers)
.expect("SPA pod bytes were produced by the matching pod serializer"),
Pod::from_bytes(&header)
.expect("SPA pod bytes were produced by the matching pod serializer"),
])
.is_err()
{
@@ -310,7 +312,9 @@ pub fn run(
*target.chunk_mut().size_mut() = 0;
return;
}
let frame = data.latest.lock().unwrap();
let frame = data.latest.lock().expect(
"capture frame state must remain consistent across producer and PipeWire callbacks",
);
if (frame.width, frame.height) != data.negotiated {
*target.chunk_mut().size_mut() = 0;
return;
@@ -344,7 +348,8 @@ pub fn run(
spa::utils::Direction::Output,
None,
pw::stream::StreamFlags::MAP_BUFFERS | pw::stream::StreamFlags::DRIVER,
&mut [Pod::from_bytes(&format).unwrap()],
&mut [Pod::from_bytes(&format)
.expect("SPA pod bytes were produced by the matching pod serializer")],
)?;
let interval = Duration::from_nanos(1_000_000_000 / 30);
@@ -362,7 +367,7 @@ pub fn run(
checked = Instant::now();
match capture.frame(&name, cursor, &capture_stop, std::mem::take(&mut spare)) {
Ok(frame) if resizable || (frame.width == width && frame.height == height) => {
spare = std::mem::replace(&mut *latest.lock().unwrap(), frame).pixels;
spare = std::mem::replace(&mut *latest.lock().expect("capture frame state must remain consistent across producer and PipeWire callbacks"), frame).pixels;
fresh.store(capture_streaming.load(Ordering::Relaxed), Ordering::SeqCst);
}
Ok(_) => {
@@ -385,12 +390,16 @@ pub fn run(
while !stop.load(Ordering::Relaxed) {
let size = {
let frame = format_frames.lock().unwrap();
let frame = format_frames.lock().expect(
"capture frame state must remain consistent across producer and PipeWire callbacks",
);
(frame.width, frame.height)
};
if resizable && size != requested_size {
let format = video_format(size.0, size.1);
if let Err(error) = stream.update_params(&mut [Pod::from_bytes(&format).unwrap()]) {
if let Err(error) = stream.update_params(&mut [Pod::from_bytes(&format)
.expect("SPA pod bytes were produced by the matching pod serializer")])
{
renegotiation_error = Some(error);
stop.store(true, Ordering::Relaxed);
break;