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.
This commit is contained in:
Yuri Astrakhan
2025-07-03 00:02:31 -04:00
parent f5a862c55d
commit c433b45682
36 changed files with 151 additions and 150 deletions
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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();
+2 -1
View File
@@ -590,7 +590,7 @@ fn write_lines<R: FdReadable>(
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<W: Write>(
writer: &mut W,
options: &OutputOptions,
@@ -634,6 +634,7 @@ fn write_end<W: Write>(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<W: Write>(in_buf: &[u8], writer: &mut W) -> usize {
// using memchr2 significantly improves performances
match memchr2(b'\n', b'\r', in_buf) {
+7 -7
View File
@@ -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.
+1 -1
View File
@@ -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<Vec<String>, ChrootError> {
let split: Vec<&str> = list_str.split(',').collect();
if split.len() == 1 {
+3 -3
View File
@@ -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,
+5 -5
View File
@@ -104,7 +104,7 @@ fn cut_bytes<R: Read, W: Write>(
Ok(())
}
// Output delimiter is explicitly specified
/// Output delimiter is explicitly specified
fn cut_fields_explicit_out_delim<R: Read, W: Write, M: Matcher>(
reader: R,
out: &mut W,
@@ -189,7 +189,7 @@ fn cut_fields_explicit_out_delim<R: Read, W: Write, M: Matcher>(
Ok(())
}
// Output delimiter is the same as input delimiter
/// Output delimiter is the same as input delimiter
fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(
reader: R,
out: &mut W,
@@ -260,7 +260,7 @@ fn cut_fields_implicit_out_delim<R: Read, W: Write, M: Matcher>(
Ok(())
}
// The input delimiter is identical to `newline_char`
/// The input delimiter is identical to `newline_char`
fn cut_fields_newline_char_delim<R: Read, W: Write>(
reader: R,
out: &mut W,
@@ -402,8 +402,8 @@ fn cut_files(mut filenames: Vec<String>, 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::<OsString>(options::DELIMITER);
+4 -4
View File
@@ -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<Num>,
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<Num>, rstat: &ReadStat) -> bool {
match count {
Some(Num::Blocks(n)) => rstat.reads_complete + rstat.reads_partial < n,
+2 -2
View File
@@ -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
+7 -7
View File
@@ -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."
/// <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."
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<Path>) -> Vec<String> {
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<Path>) -> Vec<String> {
.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<Vec<Pattern>> {
let exclude_from_iterator = matches
.get_many::<String>(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<Vec<PathBuf>, std::io::Error> {
let reader: Box<dyn BufRead> = if file_name == "-" {
// Read from standard input
+2 -2
View File
@@ -101,8 +101,8 @@ struct Options<'a> {
ignore_signal: Vec<usize>,
}
// 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();
+3 -3
View File
@@ -580,9 +580,9 @@ thread_local! {
static NODE_ID: Cell<u32> = 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();
+11 -11
View File
@@ -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<Item = &'a WordInfo<'a>>>(
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.
/// <http://onlinelibrary.wiley.com/doi/10.1002/spe.4380111102/pdf>
fn break_knuth_plass<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>(
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<Stdout>) -> 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,
+5 -5
View File
@@ -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),
+2 -2
View File
@@ -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.
+4 -4
View File
@@ -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
+5 -5
View File
@@ -123,8 +123,8 @@ impl<T: AsRef<str>> From<T> 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:<min_width$}"),
@@ -142,8 +142,8 @@ enum SectionDelimiter {
}
impl SectionDelimiter {
// A valid section delimiter contains the pattern one to three times,
// and nothing else.
/// A valid section delimiter contains the pattern one to three times,
/// and nothing else.
fn parse(s: &str, pattern: &str) -> Option<Self> {
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<T: Read>(reader: &mut BufReader<T>, stats: &mut Stats, settings: &Settings) -> UResult<()> {
let mut current_numbering_style = &settings.body_numbering;
+2 -2
View File
@@ -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(),
+3 -3
View File
@@ -107,8 +107,8 @@ fn parse_suffix(s: &str) -> Result<(f64, Option<Suffix>)> {
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);
+8 -8
View File
@@ -102,8 +102,8 @@ fn parse_unit(s: &str) -> Result<Unit> {
}
}
// 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<usize> {
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<usize> {
))
}
// 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<usize> {
if s.is_empty() {
return Some(1);

Some files were not shown because too many files have changed in this diff Show More