refact: Make the callback convert to Result<String> immediately

This is slightly easier to use than the previous pattern that was
always followed up by the same conversions.

(cherry picked from commit 756c080730cd4fa81d4c0e3a99688cbe8debe57f)
This commit is contained in:
Robert Hensing 2024-05-22 14:45:12 +02:00
parent 9a6ef0489e
commit 4688ccbf95
6 changed files with 61 additions and 43 deletions

View file

@ -1,6 +1,9 @@
use anyhow::Result;
use nix_c_raw as raw;
use nix_util::string_return::{callback_get_vec_u8, callback_get_vec_u8_data};
use nix_util::{
result_string_init,
string_return::{callback_get_result_string, callback_get_result_string_data},
};
pub struct StorePath {
raw: *mut raw::StorePath,
@ -25,13 +28,13 @@ impl StorePath {
}
pub fn name(&self) -> Result<String> {
unsafe {
let mut vec = Vec::new();
let mut r = result_string_init!();
raw::store_path_name(
self.raw,
Some(callback_get_vec_u8),
callback_get_vec_u8_data(&mut vec),
Some(callback_get_result_string),
callback_get_result_string_data(&mut r),
);
String::from_utf8(vec).map_err(|e| e.into())
r
}
}
}

View file

@ -2,7 +2,8 @@ use anyhow::{bail, Result};
use lazy_static::lazy_static;
use nix_c_raw as raw;
use nix_util::context::Context;
use nix_util::string_return::{callback_get_vec_u8, callback_get_vec_u8_data};
use nix_util::result_string_init;
use nix_util::string_return::{callback_get_result_string, callback_get_result_string_data};
use std::ffi::CString;
use std::ptr::null_mut;
use std::ptr::NonNull;
@ -78,17 +79,17 @@ impl Store {
}
pub fn get_uri(&self) -> Result<String> {
let mut raw_buffer: Vec<u8> = Vec::new();
let mut r = result_string_init!();
unsafe {
raw::store_get_uri(
self.context.ptr(),
self.inner.ptr(),
Some(callback_get_vec_u8),
callback_get_vec_u8_data(&mut raw_buffer),
Some(callback_get_result_string),
callback_get_result_string_data(&mut r),
)
};
self.context.check_err()?;
String::from_utf8(raw_buffer).map_err(|e| e.into())
r
}
}