From c433b45682cc37b01b296f4f7ad9d0b4c27fe647 Mon Sep 17 00:00:00 2001 From: Yuri Astrakhan Date: Thu, 3 Jul 2025 00:02:31 -0400 Subject: [PATCH] chore: convert comments to markdown docs A lot of functions had reasonable description using `//` instead of `///`. This PR converts them to proper markdown and fixes a few minor styling issues. --- fuzz/fuzz_targets/fuzz_split.rs | 2 +- fuzz/fuzz_targets/fuzz_wc.rs | 2 +- src/uu/cat/src/cat.rs | 3 +- src/uu/chcon/src/chcon.rs | 14 ++++---- src/uu/chroot/src/chroot.rs | 2 +- src/uu/chroot/src/error.rs | 6 ++-- src/uu/cut/src/cut.rs | 10 +++--- src/uu/dd/src/dd.rs | 8 ++--- src/uu/df/src/filesystem.rs | 4 +-- src/uu/du/src/du.rs | 14 ++++---- src/uu/env/src/env.rs | 4 +-- src/uu/expr/src/syntax_tree.rs | 6 ++-- src/uu/fmt/src/linebreak.rs | 22 ++++++------ src/uu/fmt/src/parasplit.rs | 10 +++--- src/uu/hashsum/src/hashsum.rs | 4 +-- src/uu/ls/src/ls.rs | 8 ++--- src/uu/nl/src/nl.rs | 10 +++--- src/uu/nproc/src/nproc.rs | 4 +-- src/uu/numfmt/src/format.rs | 6 ++-- src/uu/numfmt/src/numfmt.rs | 16 ++++----- src/uu/od/src/multifilereader.rs | 10 +++--- src/uu/od/src/prn_float.rs | 4 +-- src/uu/pathchk/src/pathchk.rs | 12 +++---- src/uu/seq/src/numberparse.rs | 8 ++--- src/uu/seq/src/seq.rs | 4 +-- src/uu/shred/src/shred.rs | 4 +-- src/uu/sort/src/merge.rs | 2 +- src/uu/sort/src/sort.rs | 2 +- src/uu/stty/src/stty.rs | 28 +++++++-------- src/uu/wc/src/wc.rs | 8 ++--- src/uu/yes/src/yes.rs | 6 ++-- src/uucore/src/lib/features/format/human.rs | 12 +++---- .../src/lib/features/format/num_format.rs | 2 +- src/uucore/src/lib/features/format/spec.rs | 2 +- .../src/lib/features/parser/num_parser.rs | 34 +++++++++---------- src/uucore/src/lib/mods/locale.rs | 8 ++--- 36 files changed, 151 insertions(+), 150 deletions(-) diff --git a/fuzz/fuzz_targets/fuzz_split.rs b/fuzz/fuzz_targets/fuzz_split.rs index 70860ece7..473d86f57 100644 --- a/fuzz/fuzz_targets/fuzz_split.rs +++ b/fuzz/fuzz_targets/fuzz_split.rs @@ -58,7 +58,7 @@ fn generate_split_args() -> String { args.join(" ") } -// Function to generate a random string of lines +/// Function to generate a random string of lines fn generate_random_lines(count: usize) -> String { let mut rng = rand::rng(); let mut lines = Vec::new(); diff --git a/fuzz/fuzz_targets/fuzz_wc.rs b/fuzz/fuzz_targets/fuzz_wc.rs index dbc046522..148ecdda1 100644 --- a/fuzz/fuzz_targets/fuzz_wc.rs +++ b/fuzz/fuzz_targets/fuzz_wc.rs @@ -49,7 +49,7 @@ fn generate_wc_args() -> String { args.join(" ") } -// Function to generate a random string of lines, including invalid ones +/// Function to generate a random string of lines, including invalid ones fn generate_random_lines(count: usize) -> String { let mut rng = rand::rng(); let mut lines = Vec::new(); diff --git a/src/uu/cat/src/cat.rs b/src/uu/cat/src/cat.rs index ad8fcf449..97916bbd8 100644 --- a/src/uu/cat/src/cat.rs +++ b/src/uu/cat/src/cat.rs @@ -590,7 +590,7 @@ fn write_lines( Ok(()) } -// \r followed by \n is printed as ^M when show_ends is enabled, so that \r\n prints as ^M$ +/// `\r` followed by `\n` is printed as `^M` when `show_ends` is enabled, so that `\r\n` prints as `^M$` fn write_new_line( writer: &mut W, options: &OutputOptions, @@ -634,6 +634,7 @@ fn write_end(writer: &mut W, in_buf: &[u8], options: &OutputOptions) - // We need to stop at \r because it may be written as ^M depending on the byte after and settings; // however, write_nonprint_to_end doesn't need to stop at \r because it will always write \r as ^M. // Return the number of written symbols + fn write_to_end(in_buf: &[u8], writer: &mut W) -> usize { // using memchr2 significantly improves performances match memchr2(b'\n', b'\r', in_buf) { diff --git a/src/uu/chcon/src/chcon.rs b/src/uu/chcon/src/chcon.rs index f9e3774c2..b2cddeab8 100644 --- a/src/uu/chcon/src/chcon.rs +++ b/src/uu/chcon/src/chcon.rs @@ -802,13 +802,13 @@ fn root_dev_ino_warn(dir_name: &Path) { } } -// When fts_read returns FTS_DC to indicate a directory cycle, it may or may not indicate -// a real problem. -// When a program like chgrp performs a recursive traversal that requires traversing symbolic links, -// it is *not* a problem. -// However, when invoked with "-P -R", it deserves a warning. -// The fts_options parameter records the options that control this aspect of fts behavior, -// so test that. +/// When `fts_read` returns [`fts_sys::FTS_DC`] to indicate a directory cycle, it may or may not indicate +/// a real problem. +/// When a program like chgrp performs a recursive traversal that requires traversing symbolic links, +/// it is *not* a problem. +/// However, when invoked with "-P -R", it deserves a warning. +/// The `fts_options` parameter records the options that control this aspect of fts behavior, +/// so test that. fn cycle_warning_required(fts_options: c_int, entry: &fts::EntryRef) -> bool { // When dereferencing no symlinks, or when dereferencing only those listed on the command line // and we're not processing a command-line argument, then a cycle is a serious problem. diff --git a/src/uu/chroot/src/chroot.rs b/src/uu/chroot/src/chroot.rs index 5d02384fb..2db68d6e9 100644 --- a/src/uu/chroot/src/chroot.rs +++ b/src/uu/chroot/src/chroot.rs @@ -69,7 +69,7 @@ fn parse_userspec(spec: &str) -> UserSpec { } } -// Pre-condition: `list_str` is non-empty. +/// Pre-condition: `list_str` is non-empty. fn parse_group_list(list_str: &str) -> Result, ChrootError> { let split: Vec<&str> = list_str.split(',').collect(); if split.len() == 1 { diff --git a/src/uu/chroot/src/error.rs b/src/uu/chroot/src/error.rs index 3a84f2837..c0a12b20d 100644 --- a/src/uu/chroot/src/error.rs +++ b/src/uu/chroot/src/error.rs @@ -96,9 +96,9 @@ pub enum ChrootError { } impl UError for ChrootError { - // 125 if chroot itself fails - // 126 if command is found but cannot be invoked - // 127 if command cannot be found + /// 125 if chroot itself fails + /// 126 if command is found but cannot be invoked + /// 127 if command cannot be found fn code(&self) -> i32 { match self { Self::CommandFailed(_, _) => 126, diff --git a/src/uu/cut/src/cut.rs b/src/uu/cut/src/cut.rs index c97a6b595..58de612ea 100644 --- a/src/uu/cut/src/cut.rs +++ b/src/uu/cut/src/cut.rs @@ -104,7 +104,7 @@ fn cut_bytes( Ok(()) } -// Output delimiter is explicitly specified +/// Output delimiter is explicitly specified fn cut_fields_explicit_out_delim( reader: R, out: &mut W, @@ -189,7 +189,7 @@ fn cut_fields_explicit_out_delim( Ok(()) } -// Output delimiter is the same as input delimiter +/// Output delimiter is the same as input delimiter fn cut_fields_implicit_out_delim( reader: R, out: &mut W, @@ -260,7 +260,7 @@ fn cut_fields_implicit_out_delim( Ok(()) } -// The input delimiter is identical to `newline_char` +/// The input delimiter is identical to `newline_char` fn cut_fields_newline_char_delim( reader: R, out: &mut W, @@ -402,8 +402,8 @@ fn cut_files(mut filenames: Vec, mode: &Mode) { ); } -// Get delimiter and output delimiter from `-d`/`--delimiter` and `--output-delimiter` options respectively -// Allow either delimiter to have a value that is neither UTF-8 nor ASCII to align with GNU behavior +/// Get delimiter and output delimiter from `-d`/`--delimiter` and `--output-delimiter` options respectively +/// Allow either delimiter to have a value that is neither UTF-8 nor ASCII to align with GNU behavior fn get_delimiters(matches: &ArgMatches) -> UResult<(Delimiter, Option<&[u8]>)> { let whitespace_delimited = matches.get_flag(options::WHITESPACE_DELIMITED); let delim_opt = matches.get_one::(options::DELIMITER); diff --git a/src/uu/dd/src/dd.rs b/src/uu/dd/src/dd.rs index c4261c795..824b98919 100644 --- a/src/uu/dd/src/dd.rs +++ b/src/uu/dd/src/dd.rs @@ -1338,8 +1338,8 @@ fn calc_bsize(ibs: usize, obs: usize) -> usize { (ibs / gcd) * obs } -// Calculate the buffer size appropriate for this loop iteration, respecting -// a count=N if present. +/// Calculate the buffer size appropriate for this loop iteration, respecting +/// a `count=N` if present. fn calc_loop_bsize( count: Option, rstat: &ReadStat, @@ -1362,8 +1362,8 @@ fn calc_loop_bsize( } } -// Decide if the current progress is below a count=N limit or return -// true if no such limit is set. +/// Decide if the current progress is below a `count=N` limit or return +/// `true` if no such limit is set. fn below_count_limit(count: Option, rstat: &ReadStat) -> bool { match count { Some(Num::Blocks(n)) => rstat.reads_complete + rstat.reads_partial < n, diff --git a/src/uu/df/src/filesystem.rs b/src/uu/df/src/filesystem.rs index ac9bbeaf0..53589ae8c 100644 --- a/src/uu/df/src/filesystem.rs +++ b/src/uu/df/src/filesystem.rs @@ -209,7 +209,7 @@ mod tests { use crate::filesystem::{FsError, mount_info_from_path}; - // Create a fake `MountInfo` with the given directory name. + /// Create a fake `MountInfo` with the given directory name. fn mount_info(mount_dir: &str) -> MountInfo { MountInfo { dev_id: String::default(), @@ -223,7 +223,7 @@ mod tests { } } - // Check whether two `MountInfo` instances are equal. + /// Check whether two `MountInfo` instances are equal. fn mount_info_eq(m1: &MountInfo, m2: &MountInfo) -> bool { m1.dev_id == m2.dev_id && m1.dev_name == m2.dev_name diff --git a/src/uu/du/src/du.rs b/src/uu/du/src/du.rs index 2ca50e088..a8fa90183 100644 --- a/src/uu/du/src/du.rs +++ b/src/uu/du/src/du.rs @@ -198,9 +198,9 @@ impl Stat { } #[cfg(windows)] -// https://doc.rust-lang.org/std/os/windows/fs/trait.MetadataExt.html#tymethod.last_access_time -// "The returned 64-bit value [...] which represents the number of 100-nanosecond intervals since January 1, 1601 (UTC)." -// "If the underlying filesystem does not support last access time, the returned value is 0." +/// +/// "The returned 64-bit value [...] which represents the number of 100-nanosecond intervals since January 1, 1601 (UTC)." +/// "If the underlying filesystem does not support last access time, the returned value is 0." fn windows_time_to_unix_time(win_time: u64) -> u64 { (win_time / 10_000_000).saturating_sub(11_644_473_600) } @@ -454,7 +454,7 @@ impl UError for DuError { } } -// Read a file and return each line in a vector of String +/// Read a file and return each line in a vector of String fn file_as_vec(filename: impl AsRef) -> Vec { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); @@ -464,8 +464,8 @@ fn file_as_vec(filename: impl AsRef) -> Vec { .collect() } -// Given the --exclude-from and/or --exclude arguments, returns the globset lists -// to ignore the files +/// Given the `--exclude-from` and/or `--exclude` arguments, returns the globset lists +/// to ignore the files fn build_exclude_patterns(matches: &ArgMatches) -> UResult> { let exclude_from_iterator = matches .get_many::(options::EXCLUDE_FROM) @@ -595,7 +595,7 @@ impl StatPrinter { } } -// Read file paths from the specified file, separated by null characters +/// Read file paths from the specified file, separated by null characters fn read_files_from(file_name: &str) -> Result, std::io::Error> { let reader: Box = if file_name == "-" { // Read from standard input diff --git a/src/uu/env/src/env.rs b/src/uu/env/src/env.rs index d5a7c8659..cbea4b848 100644 --- a/src/uu/env/src/env.rs +++ b/src/uu/env/src/env.rs @@ -101,8 +101,8 @@ struct Options<'a> { ignore_signal: Vec, } -// print name=value env pairs on screen -// if null is true, separate pairs with a \0, \n otherwise +/// print `name=value` env pairs on screen +/// if null is true, separate pairs with a \0, \n otherwise fn print_env(line_ending: LineEnding) { let stdout_raw = io::stdout(); let mut stdout = stdout_raw.lock(); diff --git a/src/uu/expr/src/syntax_tree.rs b/src/uu/expr/src/syntax_tree.rs index b0ae0142f..cc2ff6f83 100644 --- a/src/uu/expr/src/syntax_tree.rs +++ b/src/uu/expr/src/syntax_tree.rs @@ -580,9 +580,9 @@ thread_local! { static NODE_ID: Cell = const { Cell::new(1) }; } -// We create unique identifiers for each node in the AST. -// This is used to transform the recursive algorithm into an iterative one. -// It is used to store the result of each node's evaluation in a BtreeMap. +/// We create unique identifiers for each node in the AST. +/// This is used to transform the recursive algorithm into an iterative one. +/// It is used to store the result of each node's evaluation in a `BtreeMap`. fn get_next_id() -> u32 { NODE_ID.with(|id| { let current = id.get(); diff --git a/src/uu/fmt/src/linebreak.rs b/src/uu/fmt/src/linebreak.rs index 9dc7243cb..3ed816816 100644 --- a/src/uu/fmt/src/linebreak.rs +++ b/src/uu/fmt/src/linebreak.rs @@ -92,8 +92,8 @@ pub fn break_lines( } } -// break_simple implements a "greedy" breaking algorithm: print words until -// maxlength would be exceeded, then print a linebreak and indent and continue. +/// `break_simple` implements a "greedy" breaking algorithm: print words until +/// maxlength would be exceeded, then print a linebreak and indent and continue. fn break_simple<'a, T: Iterator>>( mut iter: T, args: &mut BreakArgs<'a>, @@ -130,10 +130,10 @@ fn accum_words_simple<'a>( } } -// break_knuth_plass implements an "optimal" breaking algorithm in the style of -// Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, -// Practice and Experience. Vol. 11, No. 11, November 1981. -// http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf +/// `break_knuth_plass` implements an "optimal" breaking algorithm in the style of +/// Knuth, D.E., and Plass, M.F. "Breaking Paragraphs into Lines." in Software, +/// Practice and Experience. Vol. 11, No. 11, November 1981. +/// fn break_knuth_plass<'a, T: Clone + Iterator>>( mut iter: T, args: &mut BreakArgs<'a>, @@ -463,7 +463,7 @@ fn restart_active_breaks<'a>( } } -// Number of spaces to add before a word, based on mode, newline, sentence start. +/// Number of spaces to add before a word, based on mode, newline, sentence start. fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { if uniform || newline { if start || (newline && punct) { 2 } else { 1 } @@ -472,8 +472,8 @@ fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize } } -// If we're on a fresh line, slen=0 and we slice off leading whitespace. -// Otherwise, compute slen and leave whitespace alone. +/// If we're on a fresh line, `slen=0` and we slice off leading whitespace. +/// Otherwise, compute `slen` and leave whitespace alone. fn slice_if_fresh( fresh: bool, word: &str, @@ -490,13 +490,13 @@ fn slice_if_fresh( } } -// Write a newline and add the indent. +/// Write a newline and add the indent. fn write_newline(indent: &str, ostream: &mut BufWriter) -> std::io::Result<()> { ostream.write_all(b"\n")?; ostream.write_all(indent.as_bytes()) } -// Write the word, along with slen spaces. +/// Write the word, along with slen spaces. fn write_with_spaces( word: &str, slen: usize, diff --git a/src/uu/fmt/src/parasplit.rs b/src/uu/fmt/src/parasplit.rs index 5911a8e47..3be410b8a 100644 --- a/src/uu/fmt/src/parasplit.rs +++ b/src/uu/fmt/src/parasplit.rs @@ -26,9 +26,9 @@ fn char_width(c: char) -> usize { } } -// GNU fmt has a more restrictive definition of whitespace than Unicode. -// It only considers ASCII whitespace characters (space, tab, newline, etc.) -// and excludes many Unicode whitespace characters like non-breaking spaces. +/// GNU fmt has a more restrictive definition of whitespace than Unicode. +/// It only considers ASCII whitespace characters (space, tab, newline, etc.) +/// and excludes many Unicode whitespace characters like non-breaking spaces. fn is_fmt_whitespace(c: char) -> bool { // Only ASCII whitespace characters are considered whitespace in GNU fmt matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C') @@ -43,7 +43,7 @@ pub enum Line { } impl Line { - // when we know that it's a FormatLine, as in the ParagraphStream iterator + /// when we know that it's a [`Line::FormatLine`], as in the [`ParagraphStream`] iterator fn get_formatline(self) -> FileLine { match self { Self::FormatLine(fl) => fl, @@ -51,7 +51,7 @@ impl Line { } } - // when we know that it's a NoFormatLine, as in the ParagraphStream iterator + /// when we know that it's a [`Line::NoFormatLine`], as in the [`ParagraphStream`] iterator fn get_noformatline(self) -> (String, bool) { match self { Self::NoFormatLine(s, b) => (s, b), diff --git a/src/uu/hashsum/src/hashsum.rs b/src/uu/hashsum/src/hashsum.rs index 1e215014a..edba539af 100644 --- a/src/uu/hashsum/src/hashsum.rs +++ b/src/uu/hashsum/src/hashsum.rs @@ -492,8 +492,8 @@ pub fn uu_app_custom() -> Command { command } -// hashsum is handled differently in build.rs, therefore this is not the same -// as in other utilities. +/// hashsum is handled differently in build.rs +/// therefore, this is different from other utilities. fn uu_app(binary_name: &str) -> (Command, bool) { match binary_name { // These all support the same options. diff --git a/src/uu/ls/src/ls.rs b/src/uu/ls/src/ls.rs index fef646a65..65e85c1f5 100644 --- a/src/uu/ls/src/ls.rs +++ b/src/uu/ls/src/ls.rs @@ -518,8 +518,8 @@ fn extract_time(options: &clap::ArgMatches) -> Time { } } -// Some env variables can be passed -// For now, we are only verifying if empty or not and known for TERM +/// Some env variables can be passed +/// For now, we are only verifying if empty or not and known for `TERM` fn is_color_compatible_term() -> bool { let is_term_set = std::env::var("TERM").is_ok(); let is_colorterm_set = std::env::var("COLORTERM").is_ok(); @@ -3322,8 +3322,8 @@ fn display_inode(metadata: &Metadata) -> String { get_inode(metadata) } -// This returns the SELinux security context as UTF8 `String`. -// In the long term this should be changed to `OsStr`, see discussions at #2621/#2656 +/// This returns the `SELinux` security context as UTF8 `String`. +/// In the long term this should be changed to [`OsStr`], see discussions at #2621/#2656 fn get_security_context(config: &Config, p_buf: &Path, must_dereference: bool) -> String { let substitute_string = "?".to_string(); // If we must dereference, ensure that the symlink is actually valid even if the system diff --git a/src/uu/nl/src/nl.rs b/src/uu/nl/src/nl.rs index 6678a1de9..ea410c83d 100644 --- a/src/uu/nl/src/nl.rs +++ b/src/uu/nl/src/nl.rs @@ -123,8 +123,8 @@ impl> From for NumberFormat { } impl NumberFormat { - // Turns a line number into a `String` with at least `min_width` chars, - // formatted according to the `NumberFormat`s variant. + /// Turns a line number into a `String` with at least `min_width` chars, + /// formatted according to the `NumberFormat`s variant. fn format(&self, number: i64, min_width: usize) -> String { match self { Self::Left => format!("{number: Option { if s.is_empty() || pattern.is_empty() { return None; @@ -335,7 +335,7 @@ pub fn uu_app() -> Command { ) } -// nl implements the main functionality for an individual buffer. +/// `nl` implements the main functionality for an individual buffer. fn nl(reader: &mut BufReader, stats: &mut Stats, settings: &Settings) -> UResult<()> { let mut current_numbering_style = &settings.body_numbering; diff --git a/src/uu/nproc/src/nproc.rs b/src/uu/nproc/src/nproc.rs index f6e84c396..29970b9a9 100644 --- a/src/uu/nproc/src/nproc.rs +++ b/src/uu/nproc/src/nproc.rs @@ -146,8 +146,8 @@ fn num_cpus_all() -> usize { available_parallelism() } -// In some cases, thread::available_parallelism() may return an Err -// In this case, we will return 1 (like GNU) +/// In some cases, [`thread::available_parallelism`]() may return an Err +/// In this case, we will return 1 (like GNU) fn available_parallelism() -> usize { match thread::available_parallelism() { Ok(n) => n.get(), diff --git a/src/uu/numfmt/src/format.rs b/src/uu/numfmt/src/format.rs index 15efa3423..27bd14bc2 100644 --- a/src/uu/numfmt/src/format.rs +++ b/src/uu/numfmt/src/format.rs @@ -107,8 +107,8 @@ fn parse_suffix(s: &str) -> Result<(f64, Option)> { Ok((number, suffix)) } -// Returns the implicit precision of a number, which is the count of digits after the dot. For -// example, 1.23 has an implicit precision of 2. +/// Returns the implicit precision of a number, which is the count of digits after the dot. For +/// example, 1.23 has an implicit precision of 2. fn parse_implicit_precision(s: &str) -> usize { match s.split_once('.') { Some((_, decimal_part)) => decimal_part @@ -217,7 +217,7 @@ pub fn div_round(n: f64, d: f64, method: RoundMethod) -> f64 { } } -// Rounds to the specified number of decimal points. +/// Rounds to the specified number of decimal points. fn round_with_precision(n: f64, method: RoundMethod, precision: usize) -> f64 { let p = 10.0_f64.powf(precision as f64); diff --git a/src/uu/numfmt/src/numfmt.rs b/src/uu/numfmt/src/numfmt.rs index 7d362981c..62100042e 100644 --- a/src/uu/numfmt/src/numfmt.rs +++ b/src/uu/numfmt/src/numfmt.rs @@ -102,8 +102,8 @@ fn parse_unit(s: &str) -> Result { } } -// Parses a unit size. Suffixes are turned into their integer representations. For example, 'K' -// will return `Ok(1000)`, and '2K' will return `Ok(2000)`. +/// Parses a unit size. Suffixes are turned into their integer representations. For example, 'K' +/// will return `Ok(1000)`, and '2K' will return `Ok(2000)`. fn parse_unit_size(s: &str) -> Result { let number: String = s.chars().take_while(char::is_ascii_digit).collect(); let suffix = &s[number.len()..]; @@ -126,12 +126,12 @@ fn parse_unit_size(s: &str) -> Result { )) } -// Parses a suffix of a unit size and returns the corresponding multiplier. For example, -// the suffix 'K' will return `Some(1000)`, and 'Ki' will return `Some(1024)`. -// -// If the suffix is empty, `Some(1)` is returned. -// -// If the suffix is unknown, `None` is returned. +/// Parses a suffix of a unit size and returns the corresponding multiplier. For example, +/// the suffix 'K' will return `Some(1000)`, and 'Ki' will return `Some(1024)`. +/// +/// If the suffix is empty, `Some(1)` is returned. +/// +/// If the suffix is unknown, `None` is returned. fn parse_unit_size_suffix(s: &str) -> Option { if s.is_empty() { return Some(1); diff --git a/src/uu/od/src/multifilereader.rs b/src/uu/od/src/multifilereader.rs index 6097c095a..7d4709ce1 100644 --- a/src/uu/od/src/multifilereader.rs +++ b/src/uu/od/src/multifilereader.rs @@ -102,11 +102,11 @@ impl MultifileReader<'_> { } impl io::Read for MultifileReader<'_> { - // Fill buf with bytes read from the list of files - // Returns Ok() - // Handles io errors itself, thus always returns OK - // Fills the provided buffer completely, unless it has run out of input. - // If any call returns short (< buf.len()), all subsequent calls will return Ok<0> + /// Fill buf with bytes read from the list of files + /// Returns `Ok()` + /// Handles io errors itself, thus always returns OK + /// Fills the provided buffer completely, unless it has run out of input. + /// If any call returns short (`< buf.len()`), all subsequent calls will return Ok<0> fn read(&mut self, buf: &mut [u8]) -> io::Result { let mut xfrd = 0; // while buffer we are filling is not full.. May go through several files. diff --git a/src/uu/od/src/prn_float.rs b/src/uu/od/src/prn_float.rs index 440333712..2530b61dc 100644 --- a/src/uu/od/src/prn_float.rs +++ b/src/uu/od/src/prn_float.rs @@ -41,8 +41,8 @@ fn format_flo16(f: f16) -> String { format_float(f64::from(f), 9, 4) } -// formats float with 8 significant digits, eg 12345678 or -1.2345678e+12 -// always returns a string of 14 characters +/// formats float with 8 significant digits, eg 12345678 or -1.2345678e+12 +/// always returns a string of 14 characters fn format_flo32(f: f32) -> String { let width: usize = 14; let precision: usize = 8; diff --git a/src/uu/pathchk/src/pathchk.rs b/src/uu/pathchk/src/pathchk.rs index 4988751d1..f22fa16a7 100644 --- a/src/uu/pathchk/src/pathchk.rs +++ b/src/uu/pathchk/src/pathchk.rs @@ -111,7 +111,7 @@ pub fn uu_app() -> Command { ) } -// check a path, given as a slice of it's components and an operating mode +/// check a path, given as a slice of it's components and an operating mode fn check_path(mode: &Mode, path: &[String]) -> bool { match *mode { Mode::Basic => check_basic(path), @@ -121,7 +121,7 @@ fn check_path(mode: &Mode, path: &[String]) -> bool { } } -// check a path in basic compatibility mode +/// check a path in basic compatibility mode fn check_basic(path: &[String]) -> bool { let joined_path = path.join("/"); let total_len = joined_path.len(); @@ -174,7 +174,7 @@ fn check_basic(path: &[String]) -> bool { check_searchable(&joined_path) } -// check a path in extra compatibility mode +/// check a path in extra compatibility mode fn check_extra(path: &[String]) -> bool { // components: leading hyphens for p in path { @@ -202,7 +202,7 @@ fn check_extra(path: &[String]) -> bool { true } -// check a path in default mode (using the file system) +/// check a path in default mode (using the file system) fn check_default(path: &[String]) -> bool { let joined_path = path.join("/"); let total_len = joined_path.len(); @@ -260,7 +260,7 @@ fn check_default(path: &[String]) -> bool { check_searchable(&joined_path) } -// check whether a path is or if other problems arise +/// check whether a path is or if other problems arise fn check_searchable(path: &str) -> bool { // we use lstat, just like the original implementation match fs::symlink_metadata(path) { @@ -276,7 +276,7 @@ fn check_searchable(path: &str) -> bool { } } -// check whether a path segment contains only valid (read: portable) characters +/// check whether a path segment contains only valid (read: portable) characters fn check_portable_chars(path_segment: &str) -> bool { const VALID_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"; for (i, ch) in path_segment.as_bytes().iter().enumerate() { diff --git a/src/uu/seq/src/numberparse.rs b/src/uu/seq/src/numberparse.rs index a53d6ee20..2777acd63 100644 --- a/src/uu/seq/src/numberparse.rs +++ b/src/uu/seq/src/numberparse.rs @@ -21,10 +21,10 @@ pub enum ParseNumberError { Nan, } -// Compute the number of integral and fractional digits in input string, -// and wrap the result in a PreciseNumber. -// We know that the string has already been parsed correctly, so we don't -// need to be too careful. +/// Compute the number of integral and fractional digits in input string, +/// and wrap the result in a PreciseNumber. +/// We know that the string has already been parsed correctly, so we don't +/// need to be too careful. fn compute_num_digits(input: &str, ebd: ExtendedBigDecimal) -> PreciseNumber { let input = input.to_lowercase(); let input = input.trim_start(); diff --git a/src/uu/seq/src/seq.rs b/src/uu/seq/src/seq.rs index db573c4d4..6fafb59c1 100644 --- a/src/uu/seq/src/seq.rs +++ b/src/uu/seq/src/seq.rs @@ -50,8 +50,8 @@ struct SeqOptions<'a> { /// The elements are (first, increment, last). type RangeFloat = (ExtendedBigDecimal, ExtendedBigDecimal, ExtendedBigDecimal); -// Turn short args with attached value, for example "-s,", into two args "-s" and "," to make -// them work with clap. +/// Turn short args with attached value, for example "-s,", into two args "-s" and "," to make +/// them work with clap. fn split_short_args_with_value(args: impl uucore::Args) -> impl uucore::Args { let mut v: Vec = Vec::new(); diff --git a/src/uu/shred/src/shred.rs b/src/uu/shred/src/shred.rs index 71810368e..0fd705b9d 100644 --- a/src/uu/shred/src/shred.rs +++ b/src/uu/shred/src/shred.rs @@ -630,8 +630,8 @@ fn do_pass( Ok(()) } -// Repeatedly renames the file with strings of decreasing length (most likely all 0s) -// Return the path of the file after its last renaming or None if error +/// Repeatedly renames the file with strings of decreasing length (most likely all 0s) +/// Return the path of the file after its last renaming or None in case of an error fn wipe_name(orig_path: &Path, verbose: bool, remove_method: RemoveMethod) -> Option { let file_name_len = orig_path.file_name().unwrap().to_str().unwrap().len(); diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index bbd0c2c83..2183517b9 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -370,7 +370,7 @@ impl Compare for FileComparator<'_> { } } -// Wait for the child to exit and check its exit code. +/// Wait for the child to exit and check its exit code. fn check_child_success(mut child: Child, program: &str) -> UResult<()> { if matches!(child.wait().map(|e| e.code()), Ok(Some(0) | None) | Err(_)) { Ok(()) diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index bc97581a5..d2675b4b2 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -978,7 +978,7 @@ impl FieldSelector { TooHigh, } - // Get the index for this line given the KeyPosition + /// Get the index for this line given the [`KeyPosition`] fn resolve_index( line: &str, tokens: Option<&[Field]>, diff --git a/src/uu/stty/src/stty.rs b/src/uu/stty/src/stty.rs index 1b0855356..a24b40c6d 100644 --- a/src/uu/stty/src/stty.rs +++ b/src/uu/stty/src/stty.rs @@ -465,8 +465,8 @@ fn stty(opts: &Options) -> UResult<()> { Ok(()) } -// GNU uses different error messages if values overflow or underflow a u8 -// this function returns the appropriate error message in the case of overflow or underflow, or u8 on success +/// GNU uses different error messages if values overflow or underflow a u8, +/// this function returns the appropriate error message in the case of overflow or underflow, or u8 on success fn parse_u8_or_err(arg: &str) -> Result { arg.parse::().map_err(|e| match e.kind() { IntErrorKind::PosOverflow => get_message_with_args( @@ -480,8 +480,8 @@ fn parse_u8_or_err(arg: &str) -> Result { }) } -// GNU uses an unsigned 32 bit integer for row/col sizes, but then wraps around 16 bits -// this function returns Some(n), where n is a u16 row/col size, or None if the string arg cannot be parsed as a u32 +/// GNU uses an unsigned 32-bit integer for row/col sizes, but then wraps around 16 bits +/// this function returns Some(n), where n is a u16 row/col size, or None if the string arg cannot be parsed as a u32 fn parse_rows_cols(arg: &str) -> Option { if let Ok(n) = arg.parse::() { return Some((n % (u16::MAX as u32 + 1)) as u16); @@ -620,7 +620,7 @@ fn string_to_baud(arg: &str) -> Option { None } -// return Some(flag) if the input is a valid flag, None if not +/// return `Some(flag)` if the input is a valid flag, `None` if not fn string_to_flag(option: &str) -> Option { let remove = option.starts_with('-'); let name = option.trim_start_matches('-'); @@ -838,15 +838,15 @@ fn apply_special_setting( Ok(()) } -// GNU stty defines some valid values for the control character mappings -// 1. Standard character, can be a a single char (ie 'C') or hat notation (ie '^C') -// 2. Integer -// a. hexadecimal, prefixed by '0x' -// b. octal, prefixed by '0' -// c. decimal, no prefix -// 3. Disabling the control character: '^-' or 'undef' -// -// This function returns the ascii value of valid control chars, or ControlCharMappingError if invalid +/// GNU stty defines some valid values for the control character mappings +/// 1. Standard character, can be a a single char (ie 'C') or hat notation (ie '^C') +/// 2. Integer +/// a. hexadecimal, prefixed by '0x' +/// b. octal, prefixed by '0' +/// c. decimal, no prefix +/// 3. Disabling the control character: '^-' or 'undef' +/// +/// This function returns the ascii value of valid control chars, or [`ControlCharMappingError`] if invalid fn string_to_control_char(s: &str) -> Result { if s == "undef" || s == "^-" || s.is_empty() { return Ok(0); diff --git a/src/uu/wc/src/wc.rs b/src/uu/wc/src/wc.rs index ec3ed5608..96a3093d7 100644 --- a/src/uu/wc/src/wc.rs +++ b/src/uu/wc/src/wc.rs @@ -162,8 +162,8 @@ impl<'a> Inputs<'a> { } } - // Creates an iterator which yields values borrowed from the command line arguments. - // Returns an error if the file specified in --files0-from cannot be opened. + /// Creates an iterator which yields values borrowed from the command line arguments. + /// Returns an error if the file specified in --files0-from cannot be opened. fn try_iter( &'a self, settings: &'a Settings<'a>, @@ -300,8 +300,8 @@ fn is_stdin_small_file() -> bool { } #[cfg(not(unix))] -// Windows presents a piped stdin as a "normal file" with a length equal to however many bytes -// have been buffered at the time it's checked. To be safe, we must never assume it's a file. +/// Windows presents a piped stdin as a "normal file" with a length equal to however many bytes +/// have been buffered at the time it's checked. To be safe, we must never assume it's a file. fn is_stdin_small_file() -> bool { false } diff --git a/src/uu/yes/src/yes.rs b/src/uu/yes/src/yes.rs index 7332297cf..0db317ba3 100644 --- a/src/uu/yes/src/yes.rs +++ b/src/uu/yes/src/yes.rs @@ -55,7 +55,7 @@ pub fn uu_app() -> Command { .infer_long_args(true) } -// Copies words from `i` into `buf`, separated by spaces. +/// Copies words from `i` into `buf`, separated by spaces. fn args_into_buffer<'a>( buf: &mut Vec, i: Option>, @@ -95,8 +95,8 @@ fn args_into_buffer<'a>( Ok(()) } -// Assumes buf holds a single output line forged from the command line arguments, copies it -// repeatedly until the buffer holds as many copies as it can under BUF_SIZE. +/// Assumes buf holds a single output line forged from the command line arguments, copies it +/// repeatedly until the buffer holds as many copies as it can under [`BUF_SIZE`]. fn prepare_buffer(buf: &mut Vec) { if buf.len() * 2 > BUF_SIZE { return; diff --git a/src/uucore/src/lib/features/format/human.rs b/src/uucore/src/lib/features/format/human.rs index 3acccf88f..3c80e0b19 100644 --- a/src/uucore/src/lib/features/format/human.rs +++ b/src/uucore/src/lib/features/format/human.rs @@ -18,12 +18,12 @@ pub enum SizeFormat { Decimal, // Powers of 1000, --si } -// There are a few peculiarities to how GNU formats the sizes: -// 1. One decimal place is given if and only if the size is smaller than 10 -// 2. It rounds sizes up. -// 3. The human-readable format uses powers for 1024, but does not display the "i" -// that is commonly used to denote Kibi, Mebi, etc. -// 4. Kibi and Kilo are denoted differently ("k" and "K", respectively) +/// There are a few peculiarities to how GNU formats the sizes: +/// 1. One decimal place is given if and only if the size is smaller than 10 +/// 2. It rounds sizes up. +/// 3. The human-readable format uses powers for 1024, but does not display the "i" +/// that is commonly used to denote Kibi, Mebi, etc. +/// 4. Kibi and Kilo are denoted differently ("k" and "K", respectively) fn format_prefixed(prefixed: &NumberPrefix) -> String { match prefixed { NumberPrefix::Standalone(bytes) => bytes.to_string(), diff --git a/src/uucore/src/lib/features/format/num_format.rs b/src/uucore/src/lib/features/format/num_format.rs index e899ff7c2..cd38b3728 100644 --- a/src/uucore/src/lib/features/format/num_format.rs +++ b/src/uucore/src/lib/features/format/num_format.rs @@ -1122,7 +1122,7 @@ mod test { assert_eq!(f(0.000001), "1e-06"); } - // Wrapper function to get a string out of Format.fmt() + /// Wrapper function to get a string out of Format.fmt() fn fmt(format: &Format, n: T) -> String where U: Formatter, diff --git a/src/uucore/src/lib/features/format/spec.rs b/src/uucore/src/lib/features/format/spec.rs index b34efd1d3..8322d26d7 100644 --- a/src/uucore/src/lib/features/format/spec.rs +++ b/src/uucore/src/lib/features/format/spec.rs @@ -563,7 +563,7 @@ fn write_padded( .map_err(FormatError::IoError) } -// Check for a number ending with a '$' +/// Check for a number ending with a '$' fn eat_argument_position(rest: &mut &[u8], index: &mut usize) -> Option { let original_index = *index; if let Some(pos) = eat_number(rest, index) { diff --git a/src/uucore/src/lib/features/parser/num_parser.rs b/src/uucore/src/lib/features/parser/num_parser.rs index 1eda08ae8..597f4b245 100644 --- a/src/uucore/src/lib/features/parser/num_parser.rs +++ b/src/uucore/src/lib/features/parser/num_parser.rs @@ -128,7 +128,7 @@ impl<'a, T> ExtendedParserError<'a, T> where T: Zero, { - // Extract the value out of an error, if possible. + /// Extract the value out of an error, if possible. fn extract(self) -> T { match self { Self::NotNumeric => T::zero(), @@ -138,9 +138,9 @@ where } } - // Map an error to another, using the provided conversion function. - // The error (self) takes precedence over errors happening during the - // conversion. + /// Map an error to another, using the provided conversion function. + /// The error (self) takes precedence over errors happening during the + /// conversion. fn map( self, f: impl FnOnce(T) -> Result>, @@ -334,7 +334,7 @@ fn parse_exponent(base: Base, str: &str) -> (Option, &str) { (None, str) } -// Parse a multiplier from allowed suffixes (e.g. s/m/h). +/// Parse a multiplier from allowed suffixes (e.g. s/m/h). fn parse_suffix_multiplier<'a>(str: &'a str, allowed_suffixes: &[(char, u32)]) -> (u32, &'a str) { if let Some(ch) = str.chars().next() { if let Some(mul) = allowed_suffixes @@ -384,8 +384,8 @@ fn parse_special_value<'a>( Err(ExtendedParserError::NotNumeric) } -// Underflow/Overflow errors always contain 0 or infinity. -// overflow: true for overflow, false for underflow. +/// Underflow/Overflow errors always contain 0 or infinity. +/// overflow: true for overflow, false for underflow. fn make_error<'a>(overflow: bool, negative: bool) -> ExtendedParserError<'a, ExtendedBigDecimal> { let mut v = if overflow { ExtendedBigDecimal::Infinity @@ -402,15 +402,15 @@ fn make_error<'a>(overflow: bool, negative: bool) -> ExtendedParserError<'a, Ext } } -// Compute bd**exp using exponentiation by squaring algorithm, while maintaining the -// precision specified in ctx (the number of digits would otherwise explode). -// -// Algorithm comes from https://en.wikipedia.org/wiki/Exponentiation_by_squaring -// -// TODO: Still pending discussion in https://github.com/akubera/bigdecimal-rs/issues/147, -// we do lose a little bit of precision, and the last digits may not be correct. -// Note: This has been copied from the latest revision in https://github.com/akubera/bigdecimal-rs/pull/148, -// so it's using minimum Rust version of `bigdecimal-rs`. +/// Compute bd**exp using exponentiation by squaring algorithm, while maintaining the +/// precision specified in ctx (the number of digits would otherwise explode). +/// +/// Algorithm comes from +/// +/// TODO: Still pending discussion in , +/// we do lose a little bit of precision, and the last digits may not be correct. +/// Note: This has been copied from the latest revision in , +/// so it's using minimum Rust version of `bigdecimal-rs`. fn pow_with_context(bd: &BigDecimal, exp: i64, ctx: &Context) -> BigDecimal { if exp == 0 { return 1.into(); @@ -467,7 +467,7 @@ fn pow_with_context(bd: &BigDecimal, exp: i64, ctx: &Context) -> BigDecimal { trim_precision(bd_x * bd_y, ctx, 0) } -// Construct an ExtendedBigDecimal based on parsed data +/// Construct an [`ExtendedBigDecimal`] based on parsed data fn construct_extended_big_decimal<'a>( digits: BigUint, negative: bool, diff --git a/src/uucore/src/lib/mods/locale.rs b/src/uucore/src/lib/mods/locale.rs index dc7a7621c..7df3559fe 100644 --- a/src/uucore/src/lib/mods/locale.rs +++ b/src/uucore/src/lib/mods/locale.rs @@ -105,7 +105,7 @@ thread_local! { static LOCALIZER: OnceLock = const { OnceLock::new() }; } -// Initialize localization with a specific locale and config +/// Initialize localization with a specific locale and config fn init_localization( locale: &LanguageIdentifier, locales_dir: &Path, @@ -135,7 +135,7 @@ fn init_localization( Ok(()) } -// Create a bundle for a specific locale +/// Create a bundle for a specific locale fn create_bundle( locale: &LanguageIdentifier, locales_dir: &Path, @@ -266,7 +266,7 @@ pub fn get_message_with_args(id: &str, ftl_args: HashMap) -> Str get_message_internal(id, Some(args)) } -// Function to detect system locale from environment variables +/// Function to detect system locale from environment variables fn detect_system_locale() -> Result { let locale_str = std::env::var("LANG") .unwrap_or_else(|_| DEFAULT_LOCALE.to_string()) @@ -410,7 +410,7 @@ mod tests { use std::path::PathBuf; use tempfile::TempDir; - // Helper function to create a temporary directory with test locale files + /// Helper function to create a temporary directory with test locale files fn create_test_locales_dir() -> TempDir { let temp_dir = TempDir::new().expect("Failed to create temp directory");