remove many unwrap and enum_value_or_default

Signed-off-by: 21pages <pages21@163.com>
This commit is contained in:
21pages
2023-07-22 14:16:41 +08:00
parent 31b3c5d721
commit aa740f4263
26 changed files with 345 additions and 191 deletions

View File

@@ -6,7 +6,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde_derive::{Deserialize, Serialize};
use tokio::{fs::File, io::*};
use crate::{bail, get_version_number, message_proto::*, ResultType, Stream};
use crate::{anyhow::anyhow, bail, get_version_number, message_proto::*, ResultType, Stream};
// https://doc.rust-lang.org/std/os/windows/fs/trait.MetadataExt.html
use crate::{
compress::{compress, decompress},
@@ -403,10 +403,18 @@ impl TransferJob {
}
if block.compressed {
let tmp = decompress(&block.data);
self.file.as_mut().unwrap().write_all(&tmp).await?;
self.file
.as_mut()
.ok_or(anyhow!("file is None"))?
.write_all(&tmp)
.await?;
self.finished_size += tmp.len() as u64;
} else {
self.file.as_mut().unwrap().write_all(&block.data).await?;
self.file
.as_mut()
.ok_or(anyhow!("file is None"))?
.write_all(&block.data)
.await?;
self.finished_size += block.data.len() as u64;
}
self.transferred += block.data.len() as u64;
@@ -456,7 +464,13 @@ impl TransferJob {
let mut compressed = false;
let mut offset: usize = 0;
loop {
match self.file.as_mut().unwrap().read(&mut buf[offset..]).await {
match self
.file
.as_mut()
.ok_or(anyhow!("file is None"))?
.read(&mut buf[offset..])
.await
{
Err(err) => {
self.file_num += 1;
self.file = None;
@@ -501,7 +515,12 @@ impl TransferJob {
async fn send_current_digest(&mut self, stream: &mut Stream) -> ResultType<()> {
let mut msg = Message::new();
let mut resp = FileResponse::new();
let meta = self.file.as_ref().unwrap().metadata().await?;
let meta = self
.file
.as_ref()
.ok_or(anyhow!("file is None"))?
.metadata()
.await?;
let last_modified = meta
.modified()?
.duration_since(SystemTime::UNIX_EPOCH)?
@@ -750,13 +769,13 @@ pub async fn handle_read_jobs(
Ok(None) => {
if job.job_completed() {
finished.push(job.id());
let err = job.job_error();
if err.is_some() {
stream
.send(&new_error(job.id(), err.unwrap(), job.file_num()))
.await?;
} else {
stream.send(&new_done(job.id(), job.file_num())).await?;
match job.job_error() {
Some(err) => {
stream
.send(&new_error(job.id(), err, job.file_num()))
.await?
}
None => stream.send(&new_done(job.id(), job.file_num())).await?,
}
} else {
// waiting confirmation.

View File

@@ -127,7 +127,7 @@ impl AddrMangle {
SocketAddr::V4(addr_v4) => {
let tm = (SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.unwrap_or(std::time::Duration::ZERO)
.as_micros() as u32) as u128;
let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
let port = addr.port() as u128;
@@ -160,9 +160,9 @@ impl AddrMangle {
if bytes.len() != 18 {
return Config::get_any_listen_addr(false);
}
let tmp: [u8; 2] = bytes[16..].try_into().unwrap();
let tmp: [u8; 2] = bytes[16..].try_into().unwrap_or_default();
let port = u16::from_le_bytes(tmp);
let tmp: [u8; 16] = bytes[..16].try_into().unwrap();
let tmp: [u8; 16] = bytes[..16].try_into().unwrap_or_default();
let ip = std::net::Ipv6Addr::from(tmp);
return SocketAddr::new(IpAddr::V6(ip), port);
}
@@ -290,16 +290,24 @@ pub fn get_time() -> i64 {
#[inline]
pub fn is_ipv4_str(id: &str) -> bool {
regex::Regex::new(r"^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d+)?$")
.unwrap()
.is_match(id)
if let Ok(reg) = regex::Regex::new(
r"^(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:\d+)?$",
) {
reg.is_match(id)
} else {
false
}
}
#[inline]
pub fn is_ipv6_str(id: &str) -> bool {
regex::Regex::new(r"^((([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4})|(\[([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4}\]:\d+))$")
.unwrap()
.is_match(id)
if let Ok(reg) = regex::Regex::new(
r"^((([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4})|(\[([a-fA-F0-9]{1,4}:{1,2})+[a-fA-F0-9]{1,4}\]:\d+))$",
) {
reg.is_match(id)
} else {
false
}
}
#[inline]
@@ -312,11 +320,13 @@ pub fn is_domain_port_str(id: &str) -> bool {
// modified regex for RFC1123 hostname. check https://stackoverflow.com/a/106223 for original version for hostname.
// according to [TLD List](https://data.iana.org/TLD/tlds-alpha-by-domain.txt) version 2023011700,
// there is no digits in TLD, and length is 2~63.
regex::Regex::new(
if let Ok(reg) = regex::Regex::new(
r"(?i)^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z-]{0,61}[a-z]:\d{1,5}$",
)
.unwrap()
.is_match(id)
) {
reg.is_match(id)
} else {
false
}
}
pub fn init_log(_is_async: bool, _name: &str) -> Option<flexi_logger::LoggerHandle> {

View File

@@ -99,9 +99,11 @@ pub extern "system" fn Java_com_carriez_flutter_1hbb_MainService_onVideoFrameUpd
buffer: JObject,
) {
let jb = JByteBuffer::from(buffer);
let data = env.get_direct_buffer_address(&jb).unwrap();
let len = env.get_direct_buffer_capacity(&jb).unwrap();
VIDEO_RAW.lock().unwrap().update(data, len);
if let Ok(data) = env.get_direct_buffer_address(&jb) {
if let Ok(len) = env.get_direct_buffer_capacity(&jb) {
VIDEO_RAW.lock().unwrap().update(data, len);
}
}
}
#[no_mangle]
@@ -111,9 +113,11 @@ pub extern "system" fn Java_com_carriez_flutter_1hbb_MainService_onAudioFrameUpd
buffer: JObject,
) {
let jb = JByteBuffer::from(buffer);
let data = env.get_direct_buffer_address(&jb).unwrap();
let len = env.get_direct_buffer_capacity(&jb).unwrap();
AUDIO_RAW.lock().unwrap().update(data, len);
if let Ok(data) = env.get_direct_buffer_address(&jb) {
if let Ok(len) = env.get_direct_buffer_capacity(&jb) {
AUDIO_RAW.lock().unwrap().update(data, len);
}
}
}
#[no_mangle]
@@ -142,12 +146,12 @@ pub extern "system" fn Java_com_carriez_flutter_1hbb_MainService_init(
ctx: JObject,
) {
log::debug!("MainService init from java");
let jvm = env.get_java_vm().unwrap();
*JVM.write().unwrap() = Some(jvm);
let context = env.new_global_ref(ctx).unwrap();
*MAIN_SERVICE_CTX.write().unwrap() = Some(context);
if let Ok(jvm) = env.get_java_vm() {
*JVM.write().unwrap() = Some(jvm);
if let Ok(context) = env.new_global_ref(ctx) {
*MAIN_SERVICE_CTX.write().unwrap() = Some(context);
}
}
}
pub fn call_main_service_mouse_input(mask: i32, x: i32, y: i32) -> JniResult<()> {

View File

@@ -19,20 +19,19 @@ use crate::{
use hbb_common::{
anyhow::anyhow,
bail,
config::PeerConfig,
log,
message_proto::{
supported_decoding::PreferCodec, video_frame, EncodedVideoFrames, Message,
SupportedDecoding, SupportedEncoding,
},
sysinfo::{System, SystemExt},
tokio::time::Instant,
ResultType,
};
#[cfg(any(feature = "hwcodec", feature = "mediacodec"))]
use hbb_common::{config::Config2, lazy_static};
use hbb_common::{
sysinfo::{System, SystemExt},
tokio::time::Instant,
};
lazy_static::lazy_static! {
static ref PEER_DECODINGS: Arc<Mutex<HashMap<i32, SupportedDecoding>>> = Default::default();
@@ -88,9 +87,9 @@ impl DerefMut for Encoder {
}
pub struct Decoder {
vp8: VpxDecoder,
vp9: VpxDecoder,
av1: AomDecoder,
vp8: Option<VpxDecoder>,
vp9: Option<VpxDecoder>,
av1: Option<AomDecoder>,
#[cfg(feature = "hwcodec")]
hw: HwDecoders,
#[cfg(feature = "hwcodec")]
@@ -279,12 +278,12 @@ impl Decoder {
let vp8 = VpxDecoder::new(VpxDecoderConfig {
codec: VpxVideoCodecId::VP8,
})
.unwrap();
.ok();
let vp9 = VpxDecoder::new(VpxDecoderConfig {
codec: VpxVideoCodecId::VP9,
})
.unwrap();
let av1 = AomDecoder::new().unwrap();
.ok();
let av1 = AomDecoder::new().ok();
Decoder {
vp8,
vp9,
@@ -314,13 +313,25 @@ impl Decoder {
) -> ResultType<bool> {
match frame {
video_frame::Union::Vp8s(vp8s) => {
Decoder::handle_vpxs_video_frame(&mut self.vp8, vp8s, rgb)
if let Some(vp8) = &mut self.vp8 {
Decoder::handle_vpxs_video_frame(vp8, vp8s, rgb)
} else {
bail!("vp8 decoder not available");
}
}
video_frame::Union::Vp9s(vp9s) => {
Decoder::handle_vpxs_video_frame(&mut self.vp9, vp9s, rgb)
if let Some(vp9) = &mut self.vp9 {
Decoder::handle_vpxs_video_frame(vp9, vp9s, rgb)
} else {
bail!("vp9 decoder not available");
}
}
video_frame::Union::Av1s(av1s) => {
Decoder::handle_av1s_video_frame(&mut self.av1, av1s, rgb)
if let Some(av1) = &mut self.av1 {
Decoder::handle_av1s_video_frame(av1, av1s, rgb)
} else {
bail!("av1 decoder not available");
}
}
#[cfg(feature = "hwcodec")]
video_frame::Union::H264s(h264s) => {

View File

@@ -129,7 +129,7 @@ impl MagInterface {
unsafe {
// load lib
let lib_file_name = "Magnification.dll";
let lib_file_name_c = CString::new(lib_file_name).unwrap();
let lib_file_name_c = CString::new(lib_file_name)?;
s.lib_handle = LoadLibraryExA(
lib_file_name_c.as_ptr() as _,
NULL,
@@ -189,7 +189,7 @@ impl MagInterface {
}
unsafe fn load_func(lib_module: HMODULE, func_name: &str) -> Result<FARPROC> {
let func_name_c = CString::new(func_name).unwrap();
let func_name_c = CString::new(func_name)?;
let func = GetProcAddress(lib_module, func_name_c.as_ptr() as _);
if func.is_null() {
return Err(Error::new(
@@ -442,7 +442,7 @@ impl CapturerMag {
}
pub(crate) fn exclude(&mut self, cls: &str, name: &str) -> Result<bool> {
let name_c = CString::new(name).unwrap();
let name_c = CString::new(name)?;
unsafe {
let mut hwnd = if cls.len() == 0 {
FindWindowExA(NULL as _, NULL as _, NULL as _, name_c.as_ptr())

View File

@@ -594,13 +594,14 @@ fn request_screen_cast(
}
let fd_res = fd_res.lock().unwrap();
let streams_res = streams_res.lock().unwrap();
if fd_res.is_some() && !streams_res.is_empty() {
Ok((conn, fd_res.clone().unwrap(), streams_res.clone()))
} else {
Err(Box::new(DBusError(
"Failed to obtain screen capture.".into(),
)))
if let Some(fd_res) = fd_res.clone() {
if !streams_res.is_empty() {
return Ok((conn, fd_res, streams_res.clone()));
}
}
Err(Box::new(DBusError(
"Failed to obtain screen capture.".into(),
)))
}
pub fn get_capturables(capture_cursor: bool) -> Result<Vec<PipeWireCapturable>, Box<dyn Error>> {

View File

@@ -30,7 +30,12 @@ fn prompt_input() -> u8 {
unsafe fn plug_in(index: idd::UINT, edid: idd::UINT) {
println!("Plug in monitor begin");
if idd::FALSE == idd::MonitorPlugIn(index, edid, 25) {
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
} else {
println!("Plug in monitor done");
@@ -46,7 +51,12 @@ unsafe fn plug_in(index: idd::UINT, edid: idd::UINT) {
sync: 60 as idd::DWORD,
});
if idd::FALSE == idd::MonitorModesUpdate(index, modes.len() as u32, modes.as_mut_ptr()) {
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
}
}
}
@@ -55,7 +65,12 @@ unsafe fn plug_in(index: idd::UINT, edid: idd::UINT) {
unsafe fn plug_out(index: idd::UINT) {
println!("Plug out monitor begin");
if idd::FALSE == idd::MonitorPlugOut(index) {
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
} else {
println!("Plug out monitor done");
}
@@ -64,7 +79,13 @@ unsafe fn plug_out(index: idd::UINT) {
fn main() {
#[cfg(windows)]
{
let abs_path = Path::new(DRIVER_INSTALL_PATH).canonicalize().unwrap();
let abs_path = match Path::new(DRIVER_INSTALL_PATH).canonicalize() {
Ok(p) => p,
Err(e) => {
println!("Failed to get absolute path of driver install: {:?}", e);
return;
}
};
unsafe {
let invalid_device = 0 as idd::HSWDEVICE;
@@ -86,7 +107,12 @@ fn main() {
if idd::InstallUpdate(full_inf_path.as_ptr() as _, &mut reboot_required)
== idd::FALSE
{
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
} else {
println!(
"Install or update driver done, reboot is {} required",
@@ -104,7 +130,12 @@ fn main() {
if idd::Uninstall(full_inf_path.as_ptr() as _, &mut reboot_required)
== idd::FALSE
{
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
} else {
println!(
"Uninstall driver done, reboot is {} required",
@@ -123,7 +154,12 @@ fn main() {
continue;
}
if idd::FALSE == idd::DeviceCreate(&mut h_sw_device) {
println!("{}", CStr::from_ptr(idd::GetLastMsg()).to_str().unwrap());
println!(
"{}",
CStr::from_ptr(idd::GetLastMsg())
.to_str()
.unwrap_or_default()
);
idd::DeviceClose(h_sw_device);
h_sw_device = invalid_device;
} else {