From 00570e0e91bf71d8aa74319ca788a1bcb40e8d2b Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Mon, 1 Mar 2021 20:46:53 -0800 Subject: [PATCH] Consolidate separate print_config functions --- src/lib.rs | 4 ++-- src/radio.rs | 42 ++++++++++++++++++++++++------------------ 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index beb9424..704528f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -155,7 +155,7 @@ pub extern "C" fn rust_main(_argc: c_int, _argv: *const *const c_char) -> c_int let filename = "device.conf"; println!("Print configuration to file '{}.", filename); - radio::print_config(&device, filename); + radio::print_config(&device, Some(filename)); } else if csv_flag { if matches.free.len() != 1 { @@ -170,7 +170,7 @@ pub extern "C" fn rust_main(_argc: c_int, _argv: *const *const c_char) -> c_int print_usage(); } let device = radio::read_image(&matches.free[0]); - radio::print_config_to_stdout(&device); + radio::print_config(&device, None); } exit(0); diff --git a/src/radio.rs b/src/radio.rs index 1504b34..537d287 100644 --- a/src/radio.rs +++ b/src/radio.rs @@ -310,32 +310,38 @@ pub fn parse_config(radio: &Radio, filename: &str) { } /// Print full information about the device configuration. -pub fn print_config(radio: &Radio, filename: &str) { +/// If `filename` is `None`, write to stdout. +pub fn print_config(radio: &Radio, filename: Option<&str>) { + + let file; + + let (fd, verbosity) = match filename { + None => { + unsafe { + let verbosity = if libc::isatty(libc::STDOUT_FILENO) == 1 { + 0 + } else { + 1 + }; + (libc::STDOUT_FILENO, verbosity) + } + }, + Some(filename) => { + file = std::fs::File::create(filename).unwrap(); + (file.as_raw_fd(), 1) + } + }; + let device = radio.ptr; - let file = std::fs::File::create(filename).unwrap(); - let fd = file.as_raw_fd(); let mode = CString::new("w").unwrap(); + unsafe { let file = libc::fdopen(fd, mode.as_ptr()); - radio_print_config(device, file, 1); + radio_print_config(device, file, verbosity); libc::fclose(file); } } -pub fn print_config_to_stdout(radio: &Radio) { - let device = radio.ptr; - let mode = CString::new("w").unwrap(); - unsafe { - let stdout = libc::fdopen(libc::STDOUT_FILENO, mode.as_ptr()); - let verbosity = if libc::isatty(libc::STDOUT_FILENO) == 1 { - 0 - } else { - 1 - }; - radio_print_config(device, stdout, verbosity); - } -} - /// Print generic information about the device. pub fn print_version(radio: &Radio) { let device = radio.ptr as *mut radio_device_t;