From 320a70bc56c3e6527bad325e0756ba010ffe17fa Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 1 Apr 2024 20:37:35 -0600 Subject: [PATCH 001/104] getopt.rs(3): initial commit --- COPYING.LESSER | 165 ++++++++++++++++ Makefile | 4 +- src/getopt-rs/error.rs | 95 --------- src/getopt-rs/errorkind.rs | 61 ------ src/getopt-rs/lib.rs | 72 ------- src/getopt-rs/opt.rs | 89 --------- src/getopt-rs/parser.rs | 382 ------------------------------------- src/getopt-rs/result.rs | 59 ------ src/getopt-rs/tests.rs | 228 ---------------------- src/getopt.rs | 115 +++++++++++ 10 files changed, 282 insertions(+), 988 deletions(-) create mode 100644 COPYING.LESSER delete mode 100644 src/getopt-rs/error.rs delete mode 100644 src/getopt-rs/errorkind.rs delete mode 100644 src/getopt-rs/lib.rs delete mode 100644 src/getopt-rs/opt.rs delete mode 100644 src/getopt-rs/parser.rs delete mode 100644 src/getopt-rs/result.rs delete mode 100644 src/getopt-rs/tests.rs create mode 100644 src/getopt.rs diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 0000000..0a04128 --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/Makefile b/Makefile index 68efd20..7f5c36f 100644 --- a/Makefile +++ b/Makefile @@ -57,9 +57,9 @@ test: build rustlibs: build/o/libsysexits.rlib build/o/libgetopt.rlib \ build/o/libstrerror.rlib -build/o/libgetopt.rlib: build src/getopt-rs/lib.rs +build/o/libgetopt.rlib: build src/getopt.rs $(RUSTC) $(RUSTFLAGS) --crate-type=lib --crate-name=getopt \ - -o $@ src/getopt-rs/lib.rs + -o $@ src/getopt.rs build/o/libstrerror.rlib: build src/strerror.rs $(RUSTC) $(RUSTFLAGS) --crate-type=lib -o $@ \ diff --git a/src/getopt-rs/error.rs b/src/getopt-rs/error.rs deleted file mode 100644 index 322af02..0000000 --- a/src/getopt-rs/error.rs +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -use std::{ error, fmt }; - -use crate::ErrorKind::{ self, * }; - -/// A basic error type for [`Parser`](struct.Parser.html) -#[derive(Debug, Eq, PartialEq)] -pub struct Error { - culprit: char, - kind: ErrorKind, -} - -impl Error { - /// Creates a new error using a known kind and the character that caused the - /// issue. - pub fn new(kind: ErrorKind, culprit: char) -> Self { - Self { culprit, kind } - } - - /// Returns the [`ErrorKind`](enum.ErrorKind.html) for this error. - pub fn kind(self) -> ErrorKind { - self.kind - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.kind { - MissingArgument => write!( - f, - "option requires an argument -- {:?}", - self.culprit, - ), - UnknownOption => write!(f, "unknown option -- {:?}", self.culprit), - } - } -} - -impl error::Error for Error { - fn source(&self) -> Option<&(dyn error::Error + 'static)> { - None - } -} diff --git a/src/getopt-rs/errorkind.rs b/src/getopt-rs/errorkind.rs deleted file mode 100644 index 5475d8e..0000000 --- a/src/getopt-rs/errorkind.rs +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/// What kinds of errors [`Parser`](struct.Parser.html) can return. -#[derive(Debug, Eq, PartialEq)] -pub enum ErrorKind { - /// An argument was not found for an option that was expecting one. - MissingArgument, - /// An unknown option character was encountered. - UnknownOption, -} diff --git a/src/getopt-rs/lib.rs b/src/getopt-rs/lib.rs deleted file mode 100644 index 62f0e0d..0000000 --- a/src/getopt-rs/lib.rs +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -//! # getopt -//! -//! `getopt` provides a minimal, (essentially) POSIX-compliant option parser. - -pub use crate::{ - error::Error, - errorkind::ErrorKind, - opt::Opt, - parser::Parser, - result::Result -}; - -mod error; -mod errorkind; -mod opt; -mod parser; -mod result; -#[cfg(test)] -mod tests; diff --git a/src/getopt-rs/opt.rs b/src/getopt-rs/opt.rs deleted file mode 100644 index 05b51e6..0000000 --- a/src/getopt-rs/opt.rs +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -use std::fmt; - -/// A single option. -/// -/// For `Opt(x, y)`: -/// - `x` is the character representing the option. -/// - `y` is `Some` string, or `None` if no argument was expected. -/// -/// # Example -/// -/// ``` -/// # fn main() -> Result<(), Box> { -/// use getopt::Opt; -/// -/// // args = ["program", "-abc", "foo"]; -/// # let args: Vec = vec!["program", "-abc", "foo"] -/// # .into_iter() -/// # .map(String::from) -/// # .collect(); -/// let optstring = "ab:c"; -/// let mut opts = getopt::Parser::new(&args, optstring); -/// -/// assert_eq!(Opt('a', None), opts.next().transpose()?.unwrap()); -/// assert_eq!(Opt('b', Some("c".to_string())), opts.next().transpose()?.unwrap()); -/// assert_eq!(None, opts.next().transpose()?); -/// # Ok(()) -/// # } -/// ``` -#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] -pub struct Opt(pub char, pub Option); - -impl fmt::Display for Opt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Opt({:?}, {:?})", self.0, self.1) - } -} diff --git a/src/getopt-rs/parser.rs b/src/getopt-rs/parser.rs deleted file mode 100644 index 6f06cc3..0000000 --- a/src/getopt-rs/parser.rs +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -use std::collections::HashMap; - -use crate::{ error::Error, errorkind::ErrorKind, opt::Opt, result::Result }; - -/// The core of the `getopt` crate. -/// -/// `Parser` is implemented as an iterator over the options present in the given -/// argument vector. -/// -/// The method [`next`](#method.next) does the heavy lifting. -/// -/// # Examples -/// -/// ## Simplified usage: -/// ``` -/// # fn main() -> Result<(), Box> { -/// use getopt::Opt; -/// -/// // args = ["program", "-abc", "foo"]; -/// # let args: Vec = vec!["program", "-abc", "foo"] -/// # .into_iter() -/// # .map(String::from) -/// # .collect(); -/// let mut opts = getopt::Parser::new(&args, "ab:c"); -/// -/// assert_eq!(Some(Opt('a', None)), opts.next().transpose()?); -/// assert_eq!(1, opts.index()); -/// assert_eq!(Some(Opt('b', Some("c".to_string()))), opts.next().transpose()?); -/// assert_eq!(2, opts.index()); -/// assert_eq!(None, opts.next()); -/// assert_eq!(2, opts.index()); -/// assert_eq!("foo", args[opts.index()]); -/// # Ok(()) -/// # } -/// ``` -/// -/// ## A more idiomatic example: -/// ``` -/// # fn main() -> Result<(), Box> { -/// use getopt::Opt; -/// -/// // args = ["program", "-abc", "-d", "foo", "-e", "bar"]; -/// # let mut args: Vec = vec!["program", "-abc", "-d", "foo", "-e", "bar"] -/// # .into_iter() -/// # .map(String::from) -/// # .collect(); -/// let mut opts = getopt::Parser::new(&args, "ab:cd:e"); -/// -/// let mut a_flag = false; -/// let mut b_flag = String::new(); -/// let mut c_flag = false; -/// let mut d_flag = String::new(); -/// let mut e_flag = false; -/// -/// loop { -/// match opts.next().transpose()? { -/// None => break, -/// Some(opt) => match opt { -/// Opt('a', None) => a_flag = true, -/// Opt('b', Some(arg)) => b_flag = arg.clone(), -/// Opt('c', None) => c_flag = true, -/// Opt('d', Some(arg)) => d_flag = arg.clone(), -/// Opt('e', None) => e_flag = true, -/// _ => unreachable!(), -/// }, -/// } -/// } -/// -/// let new_args = args.split_off(opts.index()); -/// -/// assert_eq!(true, a_flag); -/// assert_eq!("c", b_flag); -/// assert_eq!(false, c_flag); -/// assert_eq!("foo", d_flag); -/// assert_eq!(true, e_flag); -/// -/// assert_eq!(1, new_args.len()); -/// assert_eq!("bar", new_args.first().unwrap()); -/// # Ok(()) -/// # } -/// ``` -#[derive(Debug, Eq, PartialEq)] -pub struct Parser { - opts: HashMap, - args: Vec>, - index: usize, - point: usize, -} - -impl Parser { - /// Create a new `Parser`, which will process the arguments in `args` - /// according to the options specified in `optstring`. - /// - /// For compatibility with - /// [`std::env::args`](https://doc.rust-lang.org/std/env/fn.args.html), - /// valid options are expected to begin at the second element of `args`, and - /// `index` is - /// initialised to `1`. - /// If `args` is structured differently, be sure to call - /// [`set_index`](#method.set_index) before the first invocation of - /// [`next`](#method.next). - /// - /// `optstring` is a string of recognised option characters; if a character - /// is followed by a colon (`:`), that option takes an argument. - /// - /// # Note: - /// Transforming the OS-specific argument strings into a vector of `String`s - /// is the sole responsibility of the calling program, as it involves some - /// level of potential information loss (which this crate does not presume - /// to handle unilaterally) and error handling (which would complicate the - /// interface). - pub fn new(args: &[String], optstring: &str) -> Self { - let optstring: Vec = optstring.chars().collect(); - let mut opts = HashMap::new(); - let mut i = 0; - let len = optstring.len(); - - while i < len { - let j = i + 1; - - if j < len && optstring[j] == ':' { - opts.insert(optstring[i], true); - i += 1; - } else { - opts.insert(optstring[i], false); - } - i += 1; - } - - Self { - opts, - // "explode" the args into a vector of character vectors, to allow - // indexing - args: args.iter().map(|e| e.chars().collect()).collect(), - index: 1, - point: 0, - } - } - - /// Return the current `index` of the parser. - /// - /// `args[index]` will always point to the the next element of `args`; when - /// the parser is - /// finished with an element, it will increment `index`. - /// - /// After the last option has been parsed (and [`next`](#method.next) is - /// returning `None`), - /// `index` will point to the first non-option argument. - pub fn index(&self) -> usize { - self.index - } - - // `point` must be reset to 0 whenever `index` is changed - - /// Modify the current `index` of the parser. - pub fn set_index(&mut self, value: usize) { - self.index = value; - self.point = 0; - } - - /// Increment the current `index` of the parser. - /// - /// This use case is common enough to warrant its own optimised method. - pub fn incr_index(&mut self) { - self.index += 1; - self.point = 0; - } -} - -impl Iterator for Parser { - type Item = Result; - - /// Returns the next option, if any. - /// - /// Returns an [`Error`](struct.Error.html) if an unexpected option is - /// encountered or if an - /// expected argument is not found. - /// - /// Parsing stops at the first non-hyphenated argument; or at the first - /// argument matching "-"; - /// or after the first argument matching "--". - /// - /// When no more options are available, `next` returns `None`. - /// - /// # Examples - /// - /// ## "-" - /// ``` - /// use getopt::Parser; - /// - /// // args = ["program", "-", "-a"]; - /// # let args: Vec = vec!["program", "-", "-a"] - /// # .into_iter() - /// # .map(String::from) - /// # .collect(); - /// let mut opts = Parser::new(&args, "a"); - /// - /// assert_eq!(None, opts.next()); - /// assert_eq!("-", args[opts.index()]); - /// ``` - /// - /// ## "--" - /// ``` - /// use getopt::Parser; - /// - /// // args = ["program", "--", "-a"]; - /// # let args: Vec = vec!["program", "--", "-a"] - /// # .into_iter() - /// # .map(String::from) - /// # .collect(); - /// let mut opts = Parser::new(&args, "a"); - /// - /// assert_eq!(None, opts.next()); - /// assert_eq!("-a", args[opts.index()]); - /// ``` - /// - /// ## Unexpected option: - /// ``` - /// use getopt::Parser; - /// - /// // args = ["program", "-b"]; - /// # let args: Vec = vec!["program", "-b"] - /// # .into_iter() - /// # .map(String::from) - /// # .collect(); - /// let mut opts = Parser::new(&args, "a"); - /// - /// assert_eq!( - /// "unknown option -- 'b'".to_string(), - /// opts.next().unwrap().unwrap_err().to_string() - /// ); - /// ``` - /// - /// ## Missing argument: - /// ``` - /// use getopt::Parser; - /// - /// // args = ["program", "-a"]; - /// # let args: Vec = vec!["program", "-a"] - /// # .into_iter() - /// # .map(String::from) - /// # .collect(); - /// let mut opts = Parser::new(&args, "a:"); - /// - /// assert_eq!( - /// "option requires an argument -- 'a'".to_string(), - /// opts.next().unwrap().unwrap_err().to_string() - /// ); - /// ``` - fn next(&mut self) -> Option> { - if self.point == 0 { - /* - * Rationale excerpts below taken verbatim from "The Open Group Base - * Specifications Issue 7, 2018 edition", IEEE Std 1003.1-2017 - * (Revision of IEEE Std 1003.1-2008). - * Copyright © 2001-2018 IEEE and The Open Group. - */ - - /* - * If, when getopt() is called: - * argv[optind] is a null pointer - * *argv[optind] is not the character '-' - * argv[optind] points to the string "-" - * getopt() shall return -1 without changing optind. - */ - if self.index >= self.args.len() - || self.args[self.index].is_empty() - || self.args[self.index][0] != '-' - || self.args[self.index].len() == 1 - { - return None; - } - - /* - * If: - * argv[optind] points to the string "--" - * getopt() shall return -1 after incrementing index. - */ - if self.args[self.index][1] == '-' && self.args[self.index].len() == 2 { - self.incr_index(); - return None; - } - - // move past the starting '-' - self.point += 1; - } - - let opt = self.args[self.index][self.point]; - self.point += 1; - - match self.opts.get(&opt) { - None => { - if self.point >= self.args[self.index].len() { - self.incr_index(); - } - Some(Err(Error::new(ErrorKind::UnknownOption, opt))) - } - Some(false) => { - if self.point >= self.args[self.index].len() { - self.incr_index(); - } - - Some(Ok(Opt(opt, None))) - } - Some(true) => { - let arg: String = if self.point >= self.args[self.index].len() { - self.incr_index(); - if self.index >= self.args.len() { - return Some(Err(Error::new( - ErrorKind::MissingArgument, - opt, - ))); - } - self.args[self.index].iter().collect() - } else { - self.args[self.index] - .clone() - .split_off(self.point) - .iter() - .collect() - }; - - self.incr_index(); - - Some(Ok(Opt(opt, Some(arg)))) - } - } - } -} diff --git a/src/getopt-rs/result.rs b/src/getopt-rs/result.rs deleted file mode 100644 index 015a402..0000000 --- a/src/getopt-rs/result.rs +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -use std::result; - -use crate::error::Error; - -/// A specialized `Result` type for use with [`Parser`](struct.Parser.html) -pub type Result = result::Result; diff --git a/src/getopt-rs/tests.rs b/src/getopt-rs/tests.rs deleted file mode 100644 index c53d517..0000000 --- a/src/getopt-rs/tests.rs +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2023 Emma Tebibyte - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - * - * This file incorporates work covered by the following copyright and permission - * notice: - * The Clear BSD License - * - * Copyright © 2017-2023 David Wildasin - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted (subject to the limitations in the disclaimer - * below) provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions, and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of the copyright holder nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED - * BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, - * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -use crate::{Opt, Parser}; - -macro_rules! basic_test { - ($name:ident, $expect:expr, $next:expr, [$($arg:expr),+], $optstr:expr) => ( - #[test] - fn $name() -> Result<(), String> { - let expect: Option = $expect; - let args: Vec = vec![$($arg),+] - .into_iter() - .map(String::from) - .collect(); - let next: Option = $next; - let mut opts = Parser::new(&args, $optstr); - - match opts.next().transpose() { - Err(error) => { - return Err(format!("next() returned {:?}", error)) - }, - Ok(actual) => if actual != expect { - return Err( - format!("expected {:?}; got {:?}", expect, actual) - ) - }, - }; - - match next { - None => if opts.index() < args.len() { - return Err(format!( - "expected end of args; got {:?}", args[opts.index()] - )) - }, - Some(n) => if args[opts.index()] != n { - return Err(format!( - "next arg: expected {:?}; got {:?}", - n, - args[opts.index()] - )) - }, - }; - - Ok(()) - } - ) -} - -#[rustfmt::skip] basic_test!( - blank_arg, None, Some(String::new()), ["x", ""], "a" -); -#[rustfmt::skip] basic_test!( - double_dash, None, Some("-a".to_string()), ["x", "--", "-a", "foo"], "a" -); -#[rustfmt::skip] basic_test!(no_opts_1, None, None, ["x"], "a"); -#[rustfmt::skip] basic_test!( - no_opts_2, None, Some("foo".to_string()), ["x", "foo"], "a" -); -#[rustfmt::skip] basic_test!( - no_opts_3, None, Some("foo".to_string()), ["x", "foo", "-a"], "a" -); -#[rustfmt::skip] basic_test!( - single_dash, None, Some("-".to_string()), ["x", "-", "-a", "foo"], "a" -); -#[rustfmt::skip] basic_test!( - single_opt, - Some(Opt('a', None)), - Some("foo".to_string()), - ["x", "-a", "foo"], - "a" -); -#[rustfmt::skip] basic_test!( - single_optarg, - Some(Opt('a', Some("foo".to_string()))), - None, - ["x", "-a", "foo"], - "a:" -); - -macro_rules! error_test { - ($name:ident, $expect:expr, [$($arg:expr),+], $optstr:expr) => ( - #[test] - fn $name() -> Result<(), String> { - let expect: String = $expect.to_string(); - let args: Vec = vec![$($arg),+] - .into_iter() - .map(String::from) - .collect(); - let mut opts = Parser::new(&args, $optstr); - - match opts.next() { - None => { - return Err(format!( - "unexpected successful response: end of options" - )) - }, - Some(Err(actual)) => { - let actual = actual.to_string(); - - if actual != expect { - return Err( - format!("expected {:?}; got {:?}", expect, actual) - ); - } - }, - Some(Ok(opt)) => { - return Err( - format!("unexpected successful response: {:?}", opt) - ) - }, - }; - - Ok(()) - } - ) -} - -#[rustfmt::skip] error_test!( - bad_opt, - "unknown option -- 'b'", - ["x", "-b"], - "a" -); - -#[rustfmt::skip] error_test!( - missing_optarg, - "option requires an argument -- 'a'", - ["x", "-a"], - "a:" -); - -#[test] -fn multiple() -> Result<(), String> { - let args: Vec = vec!["x", "-abc", "-d", "foo", "-e", "bar"] - .into_iter() - .map(String::from) - .collect(); - let optstring = "ab:d:e".to_string(); - let mut opts = Parser::new(&args, &optstring); - - macro_rules! check_result { - ($expect:expr) => { - let expect: Option = $expect; - match opts.next().transpose() { - Err(error) => { - return Err(format!("next() returned {:?}", error)); - }, - Ok(actual) => { - if actual != expect { - return Err( - format!("expected {:?}; got {:?}", expect, actual) - ); - } - } - }; - }; - } - - check_result!(Some(Opt('a', None))); - check_result!(Some(Opt('b', Some("c".to_string())))); - check_result!(Some(Opt('d', Some("foo".to_string())))); - check_result!(Some(Opt('e', None))); - check_result!(None); - - Ok(()) -} - -#[test] -fn continue_after_error() { - let args: Vec = vec!["x", "-z", "-abc"] - .into_iter() - .map(String::from) - .collect(); - let optstring = "ab:d:e".to_string(); - for _opt in Parser::new(&args, &optstring) { - // do nothing, should not panic - } -} diff --git a/src/getopt.rs b/src/getopt.rs new file mode 100644 index 0000000..f7668c6 --- /dev/null +++ b/src/getopt.rs @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2024 Emma Tebibyte + * SPDX-License-Identifier: LGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see https://www.gnu.org/licenses/. + */ + +use std::ffi::{ c_int, c_char, CString }; + +pub struct Opt { + pub arg: Option, + pub ind: i32, + pub opt: i32, +} + +pub enum OptError { + MissingArg, + UnknownOpt, +} + +// Function signature +pub trait GetOpt { + fn getopt( + argv: Vec, + optstring: &str + ) -> Option>; +} + +impl GetOpt for Vec { + fn getopt( + argv: Vec, + optstring: &str + ) -> Option> { + unsafe { + let args = argv + .iter() + .cloned() + .map(CString::new) + .map(Result::unwrap) + .map(|x| x.as_ptr() as c_char) + .collect::>() + .as_ptr() as *const *mut c_char; + + let len = argv.len() as c_int; + let opts = CString::new(optstring).unwrap().into_raw(); + + let a = match getopt(len, args, opts) { + /* From getopt(3p): + * + * The getopt() function shall return the next option character + * specified on the command line. + * + * A (':') shall be returned if getopt() detects a + * missing argument and the first character of optstring was a + * (':'). + * + * A ('?') shall be returned if getopt() + * encounters an option character not in optstring or detects a + * missing argument and the first character of optstring was not + * a (':'). + * + * Otherwise, getopt() shall return -1 when all command line + * options are parsed. */ + 58 => { // ASCII value for ':' + return Some(Err(OptError::MissingArg)); + }, + 63 => { // ASCII value for '?' + return Some(Err(OptError::UnknownOpt)); + }, + /* From getopt(3p): + * + * If, when getopt() is called: + * + * argv[optind] is a null pointer + * *argv[optind] is not the character - + * argv[optind] points to the string "-" + * + * getopt() shall return -1 without changing optind. If: + * + * argv[optind] points to the string "--" + * + * getopt() shall return -1 after incrementing optind. */ + -1 => return None, + a => a.to_string(), + }; + + Some(Ok(Opt { arg: Some(a), ind: optind, opt: optopt })) + } + } +} + +/* binding to getopt(3p) */ +extern "C" { + static mut _optarg: *mut c_char; + static mut _opterr: c_int; + static mut optind: c_int; + static mut optopt: c_int; + + fn getopt( + ___argc: c_int, + ___argv: *const *mut c_char, + __shortopts: *const c_char, + ) -> c_int; +} From 0164b681c03604f2532d97f52ba0061ef23beaf4 Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 1 Apr 2024 20:41:07 -0600 Subject: [PATCH 002/104] Makefile: remove unneeded test --- Makefile | 1 - 1 file changed, 1 deletion(-) diff --git a/Makefile b/Makefile index 7f5c36f..7736a78 100644 --- a/Makefile +++ b/Makefile @@ -51,7 +51,6 @@ install: dist .PHONY: test test: build tests/posix-compat.sh - $(RUSTC) --test src/getopt-rs/lib.rs -o build/test/getopt .PHONY: rustlibs rustlibs: build/o/libsysexits.rlib build/o/libgetopt.rlib \ From 88b0d5544001d326496b335bf626562c68481c1c Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 11 Apr 2024 20:21:01 -0600 Subject: [PATCH 003/104] getopt.rs(3): refactor to remove as much as possible from unsafe --- src/getopt.rs | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index f7668c6..b95108c 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -31,31 +31,24 @@ pub enum OptError { // Function signature pub trait GetOpt { - fn getopt( - argv: Vec, - optstring: &str - ) -> Option>; + fn getopt(&self, optstring: &str) -> Option>; } impl GetOpt for Vec { - fn getopt( - argv: Vec, - optstring: &str - ) -> Option> { + fn getopt(&self, optstring: &str) -> Option> { + let argv = self + .iter() + .cloned() + .map(CString::new) + .map(Result::unwrap) + .map(|x| x.as_ptr() as c_char) + .collect::>() + .as_ptr() as *const *mut c_char; + let opts = CString::new(optstring).unwrap().into_raw(); + let len = self.len() as c_int; + unsafe { - let args = argv - .iter() - .cloned() - .map(CString::new) - .map(Result::unwrap) - .map(|x| x.as_ptr() as c_char) - .collect::>() - .as_ptr() as *const *mut c_char; - - let len = argv.len() as c_int; - let opts = CString::new(optstring).unwrap().into_raw(); - - let a = match getopt(len, args, opts) { + let a = match getopt(len, argv, opts) { /* From getopt(3p): * * The getopt() function shall return the next option character From bb2c63bfafc19cd468b7fb9ebbdb3dd4e411d2b4 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 11 Apr 2024 20:33:42 -0600 Subject: [PATCH 004/104] getopt.rs(3): fixed pointer shenanigans --- src/getopt.rs | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index b95108c..81c146d 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -16,7 +16,7 @@ * along with this program. If not, see https://www.gnu.org/licenses/. */ -use std::ffi::{ c_int, c_char, CString }; +use std::ffi::{ c_int, c_char, CString, CStr }; pub struct Opt { pub arg: Option, @@ -35,20 +35,22 @@ pub trait GetOpt { } impl GetOpt for Vec { - fn getopt(&self, optstring: &str) -> Option> { - let argv = self + fn getopt(&self, optstring: &str) -> Option> { + let c_strings: Vec<_> = self .iter() .cloned() .map(CString::new) .map(Result::unwrap) - .map(|x| x.as_ptr() as c_char) - .collect::>() - .as_ptr() as *const *mut c_char; - let opts = CString::new(optstring).unwrap().into_raw(); - let len = self.len() as c_int; + .collect(); - unsafe { - let a = match getopt(len, argv, opts) { + let argv: Vec<_> = c_strings.iter().map(|x| x.as_ptr()).collect(); + let argv_ptr = argv.as_ptr() as *const *mut c_char; + let optstring_c = CString::new(optstring).unwrap(); + let opts = optstring_c.into_raw(); + let len = self.len() as c_int; + + unsafe { + let a = match getopt(len, argv_ptr, opts) { /* From getopt(3p): * * The getopt() function shall return the next option character @@ -65,11 +67,11 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { // ASCII value for ':' + 58 => { /* ASCII value for ':' */ return Some(Err(OptError::MissingArg)); }, - 63 => { // ASCII value for '?' - return Some(Err(OptError::UnknownOpt)); + 63 => { /* ASCII value for '?' */ + return Some(Err(OptError::UnknownOpt)) }, /* From getopt(3p): * @@ -84,18 +86,17 @@ impl GetOpt for Vec { * argv[optind] points to the string "--" * * getopt() shall return -1 after incrementing optind. */ - -1 => return None, - a => a.to_string(), - }; + -1 => return None, + _ => CStr::from_ptr(optarg).to_string_lossy().into_owned(), + }; - Some(Ok(Opt { arg: Some(a), ind: optind, opt: optopt })) - } - } + Some(Ok(Opt { arg: Some(a), ind: optind, opt: optopt })) + } + } } - /* binding to getopt(3p) */ extern "C" { - static mut _optarg: *mut c_char; + static mut optarg: *mut c_char; static mut _opterr: c_int; static mut optind: c_int; static mut optopt: c_int; From ad92fe27d4eb2a6731182844918713ee93acc292 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 11 Apr 2024 23:37:04 -0600 Subject: [PATCH 005/104] fop(1): switch to getopt.rs(3) --- src/fop.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/fop.rs b/src/fop.rs index b829602..a56a0a6 100644 --- a/src/fop.rs +++ b/src/fop.rs @@ -26,33 +26,43 @@ extern crate getopt; extern crate strerror; extern crate sysexits; -use getopt::{ Opt, Parser }; +use getopt::GetOpt; use strerror::StrError; use sysexits::{ EX_DATAERR, EX_IOERR, EX_UNAVAILABLE, EX_USAGE }; fn main() { let argv = args().collect::>(); let mut d = '␞'; - let mut arg_parser = Parser::new(&argv, "d:"); + let usage = format!( + "Usage: {} [-d delimiter] index command [args...]", + argv[0], + ); + let mut index_arg = 0; - while let Some(opt) = arg_parser.next() { + while let Some(opt) = argv.getopt("d:") { match opt { - Ok(Opt('d', Some(arg))) => { + Ok(o) => { + /* unwrap because Err(OptError::MissingArg) will be returned if + * o.arg is None */ + let arg = o.arg.unwrap(); let arg_char = arg.chars().collect::>(); if arg_char.len() > 1 { eprintln!("{}: {}: Not a character.", argv[0], arg); exit(EX_USAGE); } else { d = arg_char[0]; } + index_arg = o.ind as usize; }, - _ => {}, + Err(_) => { + eprintln!("{}", usage); + exit(EX_USAGE); + } }; } - let index_arg = arg_parser.index(); - let command_arg = arg_parser.index() + 1; + let command_arg = index_arg as usize + 1; argv.get(command_arg).unwrap_or_else(|| { - eprintln!("Usage: {} [-d delimiter] index command [args...]", argv[0]); + eprintln!("{}", usage); exit(EX_USAGE); }); From 95927ba8c5125893dbc5a92d2022ed710df7211e Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 11 Apr 2024 23:51:52 -0600 Subject: [PATCH 006/104] getopt.rs(3): formatting --- src/getopt.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 81c146d..70ee801 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -29,7 +29,7 @@ pub enum OptError { UnknownOpt, } -// Function signature +/* function signature */ pub trait GetOpt { fn getopt(&self, optstring: &str) -> Option>; } @@ -43,10 +43,11 @@ impl GetOpt for Vec { .map(Result::unwrap) .collect(); + /* these operations must be separated out into separate operations so + * the CStrings can live long enough */ let argv: Vec<_> = c_strings.iter().map(|x| x.as_ptr()).collect(); let argv_ptr = argv.as_ptr() as *const *mut c_char; - let optstring_c = CString::new(optstring).unwrap(); - let opts = optstring_c.into_raw(); + let opts = CString::new(optstring).unwrap().into_raw(); let len = self.len() as c_int; unsafe { @@ -67,10 +68,10 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { /* ASCII value for ':' */ + 58 => { /* numerical ASCII value for ':' */ return Some(Err(OptError::MissingArg)); }, - 63 => { /* ASCII value for '?' */ + 63 => { /* numerical ASCII value for '?' */ return Some(Err(OptError::UnknownOpt)) }, /* From getopt(3p): From 8c255e61fc4d35ed250b36f4ecf2a8e17edef5d7 Mon Sep 17 00:00:00 2001 From: emma Date: Fri, 12 Apr 2024 00:12:37 -0600 Subject: [PATCH 007/104] COPYING.GPL: initial commit --- COPYING.GPL | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 COPYING.GPL diff --git a/COPYING.GPL b/COPYING.GPL new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/COPYING.GPL @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From d1b77d652b18980f45e6a5a19d9a00e5b3b85f2b Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 13 Apr 2024 17:11:04 -0600 Subject: [PATCH 008/104] getopt.rs(3): returns last parsed option --- src/getopt.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 70ee801..c4f88ab 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -21,12 +21,13 @@ use std::ffi::{ c_int, c_char, CString, CStr }; pub struct Opt { pub arg: Option, pub ind: i32, - pub opt: i32, + /* opt is set to either the current option or the one that cause an error */ + pub opt: String, } pub enum OptError { - MissingArg, - UnknownOpt, + MissingArg(String), + UnknownOpt(String), } /* function signature */ @@ -51,7 +52,7 @@ impl GetOpt for Vec { let len = self.len() as c_int; unsafe { - let a = match getopt(len, argv_ptr, opts) { + match getopt(len, argv_ptr, opts) { /* From getopt(3p): * * The getopt() function shall return the next option character @@ -69,10 +70,10 @@ impl GetOpt for Vec { * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ 58 => { /* numerical ASCII value for ':' */ - return Some(Err(OptError::MissingArg)); + Some(Err(OptError::MissingArg(optopt.to_string()))) }, 63 => { /* numerical ASCII value for '?' */ - return Some(Err(OptError::UnknownOpt)) + Some(Err(OptError::UnknownOpt(optopt.to_string()))) }, /* From getopt(3p): * @@ -88,10 +89,18 @@ impl GetOpt for Vec { * * getopt() shall return -1 after incrementing optind. */ -1 => return None, - _ => CStr::from_ptr(optarg).to_string_lossy().into_owned(), - }; + opt => { + let arg = CStr::from_ptr(optarg) + .to_string_lossy() + .into_owned(); - Some(Ok(Opt { arg: Some(a), ind: optind, opt: optopt })) + Some(Ok(Opt { + arg: Some(arg), + ind: optind, + opt: opt.to_string(), + })) + }, + } } } } From 78eacd660a3af310bae8c23b1693e20e56d49896 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 13 Apr 2024 23:42:11 -0600 Subject: [PATCH 009/104] getopt.rs(3): better Opt return --- src/getopt.rs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index c4f88ab..b146400 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -21,7 +21,6 @@ use std::ffi::{ c_int, c_char, CString, CStr }; pub struct Opt { pub arg: Option, pub ind: i32, - /* opt is set to either the current option or the one that cause an error */ pub opt: String, } @@ -51,8 +50,8 @@ impl GetOpt for Vec { let opts = CString::new(optstring).unwrap().into_raw(); let len = self.len() as c_int; - unsafe { - match getopt(len, argv_ptr, opts) { + unsafe { // TODO: enable optind modification + match getopt(len, argv_ptr, opts) { /* From getopt(3p): * * The getopt() function shall return the next option character @@ -95,9 +94,9 @@ impl GetOpt for Vec { .into_owned(); Some(Ok(Opt { - arg: Some(arg), - ind: optind, - opt: opt.to_string(), + arg: Some(arg), /* opt argument */ + ind: optind, /* opt index */ + opt: opt.to_string(), /* option itself */ })) }, } From a5a9c91cb6f18159e39c87143ece06a4ceb8d7df Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 4 Jun 2024 14:28:19 -0600 Subject: [PATCH 010/104] getopt.rs(3): optind support --- src/getopt.rs | 49 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index b146400..79879df 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -18,6 +18,21 @@ use std::ffi::{ c_int, c_char, CString, CStr }; + +/* binding to getopt(3p) */ +extern "C" { + static mut optarg: *mut c_char; + static mut _opterr: c_int; + static mut optind: c_int; + static mut optopt: c_int; + + fn getopt( + ___argc: c_int, + ___argv: *const *mut c_char, + __shortopts: *const c_char, + ) -> c_int; +} + pub struct Opt { pub arg: Option, pub ind: i32, @@ -50,7 +65,7 @@ impl GetOpt for Vec { let opts = CString::new(optstring).unwrap().into_raw(); let len = self.len() as c_int; - unsafe { // TODO: enable optind modification + unsafe { match getopt(len, argv_ptr, opts) { /* From getopt(3p): * @@ -103,16 +118,24 @@ impl GetOpt for Vec { } } } -/* binding to getopt(3p) */ -extern "C" { - static mut optarg: *mut c_char; - static mut _opterr: c_int; - static mut optind: c_int; - static mut optopt: c_int; - fn getopt( - ___argc: c_int, - ___argv: *const *mut c_char, - __shortopts: *const c_char, - ) -> c_int; -} +/* From getopt(3p): + * + * The variable optind is the index of the next element of the argv[] + * vector to be processed. It shall be initialized to 1 by the system, and + * getopt() shall update it when it finishes with each element of argv[]. + * If the application sets optind to zero before calling getopt(), the + * behavior is unspecified. When an element of argv[] contains multiple + * option characters, it is unspecified how getopt() determines which + * options have already been processed. + * + * This API can be utilized using unsafe blocks and dereferencing: + * + * use getopt::OPTIND; + * + * unsafe { while *OPTIND < 5 { + * println!("{}", *OPTIND); // 1..4 + * *OPTIND += 1; + * }} + */ +pub static mut OPTIND: *mut i32 = unsafe { std::ptr::addr_of_mut!(optind) }; From b7283d54fe42fe7d6ac3899c2e6ea1fea55552f6 Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 4 Jun 2024 15:07:11 -0600 Subject: [PATCH 011/104] getopt.rs(3): formatting & organization --- src/getopt.rs | 55 +++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 79879df..0324f87 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -18,7 +18,6 @@ use std::ffi::{ c_int, c_char, CString, CStr }; - /* binding to getopt(3p) */ extern "C" { static mut optarg: *mut c_char; @@ -33,6 +32,27 @@ extern "C" { ) -> c_int; } +/* From getopt(3p): + * + * The variable optind is the index of the next element of the argv[] + * vector to be processed. It shall be initialized to 1 by the system, and + * getopt() shall update it when it finishes with each element of argv[]. + * If the application sets optind to zero before calling getopt(), the + * behavior is unspecified. When an element of argv[] contains multiple + * option characters, it is unspecified how getopt() determines which + * options have already been processed. + * + * This API can be utilized using unsafe blocks and dereferencing: + * + * use getopt::OPTIND; + * + * unsafe { while *OPTIND < 5 { + * println!("{}", *OPTIND); // 1..4 + * *OPTIND += 1; + * }} + */ +pub static mut OPTIND: *mut i32 = unsafe { std::ptr::addr_of_mut!(optind) }; + pub struct Opt { pub arg: Option, pub ind: i32, @@ -83,12 +103,12 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { /* numerical ASCII value for ':' */ - Some(Err(OptError::MissingArg(optopt.to_string()))) - }, - 63 => { /* numerical ASCII value for '?' */ - Some(Err(OptError::UnknownOpt(optopt.to_string()))) - }, + 58 => { /* numerical ASCII value for ':' */ + Some(Err(OptError::MissingArg(optopt.to_string()))) + }, + 63 => { /* numerical ASCII value for '?' */ + Some(Err(OptError::UnknownOpt(optopt.to_string()))) + }, /* From getopt(3p): * * If, when getopt() is called: @@ -118,24 +138,3 @@ impl GetOpt for Vec { } } } - -/* From getopt(3p): - * - * The variable optind is the index of the next element of the argv[] - * vector to be processed. It shall be initialized to 1 by the system, and - * getopt() shall update it when it finishes with each element of argv[]. - * If the application sets optind to zero before calling getopt(), the - * behavior is unspecified. When an element of argv[] contains multiple - * option characters, it is unspecified how getopt() determines which - * options have already been processed. - * - * This API can be utilized using unsafe blocks and dereferencing: - * - * use getopt::OPTIND; - * - * unsafe { while *OPTIND < 5 { - * println!("{}", *OPTIND); // 1..4 - * *OPTIND += 1; - * }} - */ -pub static mut OPTIND: *mut i32 = unsafe { std::ptr::addr_of_mut!(optind) }; From 35ddc729fdc78334ab3656094ca0c6b81f32ca2d Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 4 Jun 2024 19:15:22 -0600 Subject: [PATCH 012/104] getopt.rs(3): makes optind part of the Opt struct --- src/getopt.rs | 42 ++++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 0324f87..62696e0 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -32,30 +32,9 @@ extern "C" { ) -> c_int; } -/* From getopt(3p): - * - * The variable optind is the index of the next element of the argv[] - * vector to be processed. It shall be initialized to 1 by the system, and - * getopt() shall update it when it finishes with each element of argv[]. - * If the application sets optind to zero before calling getopt(), the - * behavior is unspecified. When an element of argv[] contains multiple - * option characters, it is unspecified how getopt() determines which - * options have already been processed. - * - * This API can be utilized using unsafe blocks and dereferencing: - * - * use getopt::OPTIND; - * - * unsafe { while *OPTIND < 5 { - * println!("{}", *OPTIND); // 1..4 - * *OPTIND += 1; - * }} - */ -pub static mut OPTIND: *mut i32 = unsafe { std::ptr::addr_of_mut!(optind) }; - pub struct Opt { pub arg: Option, - pub ind: i32, + pub ind: *mut i32, pub opt: String, } @@ -89,7 +68,7 @@ impl GetOpt for Vec { match getopt(len, argv_ptr, opts) { /* From getopt(3p): * - * The getopt() function shall return the next option character + * The getopt() f unction shall return the next option character * specified on the command line. * * A (':') shall be returned if getopt() detects a @@ -130,7 +109,22 @@ impl GetOpt for Vec { Some(Ok(Opt { arg: Some(arg), /* opt argument */ - ind: optind, /* opt index */ + /* From getopt(3p): + * + * The variable optind is the index of the next element + * of the argv[] vector to be processed. It shall be + * initialized to 1 by the system, and getopt() shall + * update it when it finishes with each element of + * argv[]. If the application sets optind to zero + * before calling getopt(), the behavior is unspecified. + * When an element of argv[] contains multiple option + * characters, it is unspecified how getopt() + * determines which options have already been processed. + * + * This API is unsafe and can be utilized by + * dereferencing the ind field before reading to and + * writing from the optind memory. */ + ind: std::ptr::addr_of_mut!(optind), opt: opt.to_string(), /* option itself */ })) }, From 05cde15105239a1fc960c2563826dc367e11bd0b Mon Sep 17 00:00:00 2001 From: emma Date: Tue, 4 Jun 2024 19:15:55 -0600 Subject: [PATCH 013/104] fop(1): updated to use new optind api --- src/fop.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fop.rs b/src/fop.rs index a56a0a6..8ffb447 100644 --- a/src/fop.rs +++ b/src/fop.rs @@ -50,7 +50,7 @@ fn main() { eprintln!("{}: {}: Not a character.", argv[0], arg); exit(EX_USAGE); } else { d = arg_char[0]; } - index_arg = o.ind as usize; + unsafe { index_arg = *o.ind as usize; } }, Err(_) => { eprintln!("{}", usage); From e862b7fec6a1fa12222ce298b4df8c9cdbee7d89 Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 5 Jun 2024 11:54:55 -0600 Subject: [PATCH 014/104] getopt.rs(3): safe api around optind reading and setting --- src/getopt.rs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index 62696e0..dca53e0 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -34,10 +34,16 @@ extern "C" { pub struct Opt { pub arg: Option, - pub ind: *mut i32, + ind: *mut i32, pub opt: String, } +impl Opt { + pub fn index(&self) -> usize { unsafe { *self.ind as usize } } + + pub fn set_index(&self, ind: i32) { unsafe { *self.ind = ind; } } +} + pub enum OptError { MissingArg(String), UnknownOpt(String), @@ -82,12 +88,12 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { /* numerical ASCII value for ':' */ - Some(Err(OptError::MissingArg(optopt.to_string()))) - }, - 63 => { /* numerical ASCII value for '?' */ - Some(Err(OptError::UnknownOpt(optopt.to_string()))) - }, + 58 => { /* numerical ASCII value for ':' */ + Some(Err(OptError::MissingArg(optopt.to_string()))) + }, + 63 => { /* numerical ASCII value for '?' */ + Some(Err(OptError::UnknownOpt(optopt.to_string()))) + }, /* From getopt(3p): * * If, when getopt() is called: @@ -121,9 +127,8 @@ impl GetOpt for Vec { * characters, it is unspecified how getopt() * determines which options have already been processed. * - * This API is unsafe and can be utilized by - * dereferencing the ind field before reading to and - * writing from the optind memory. */ + * This API is can be utilized with the index() and + * set_index() methods implemented for Opt. */ ind: std::ptr::addr_of_mut!(optind), opt: opt.to_string(), /* option itself */ })) From 02daca87dcd3a098d0c85b5021949a8e731d2947 Mon Sep 17 00:00:00 2001 From: emma Date: Wed, 5 Jun 2024 11:55:16 -0600 Subject: [PATCH 015/104] fop(1): updated to latest optind api --- src/fop.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fop.rs b/src/fop.rs index 8ffb447..e0bba4c 100644 --- a/src/fop.rs +++ b/src/fop.rs @@ -44,13 +44,13 @@ fn main() { Ok(o) => { /* unwrap because Err(OptError::MissingArg) will be returned if * o.arg is None */ - let arg = o.arg.unwrap(); + let arg = o.arg.clone().unwrap(); let arg_char = arg.chars().collect::>(); if arg_char.len() > 1 { eprintln!("{}: {}: Not a character.", argv[0], arg); exit(EX_USAGE); } else { d = arg_char[0]; } - unsafe { index_arg = *o.ind as usize; } + index_arg = o.index(); }, Err(_) => { eprintln!("{}", usage); From 40da8135f189db009dfb24bbc1c3ccc7e2879ed1 Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 6 Jun 2024 01:03:01 -0600 Subject: [PATCH 016/104] getopt.rs(3): relicense to AGPLv3 --- COPYING.GPL | 674 ------------------------------------------------- COPYING.LESSER | 165 ------------ src/getopt.rs | 10 +- 3 files changed, 5 insertions(+), 844 deletions(-) delete mode 100644 COPYING.GPL delete mode 100644 COPYING.LESSER diff --git a/COPYING.GPL b/COPYING.GPL deleted file mode 100644 index f288702..0000000 --- a/COPYING.GPL +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index 0a04128..0000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/src/getopt.rs b/src/getopt.rs index dca53e0..5ce094c 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -1,18 +1,18 @@ /* - * Copyright (c) 2024 Emma Tebibyte - * SPDX-License-Identifier: LGPL-3.0-or-later + * Copyright (c) 2023–2024 Emma Tebibyte + * SPDX-License-Identifier: AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free + * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * - * You should have received a copy of the GNU Lesser General Public License + * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. */ From 8f990ba515ccdb548b8f4a858e128e204842fcbd Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 22 Jun 2024 22:18:13 -0600 Subject: [PATCH 017/104] getopt.rs(3): adds testing --- Makefile | 6 +- src/getopt.rs | 151 +++++++++++++++++++++++++++++++++++--------------- 2 files changed, 111 insertions(+), 46 deletions(-) diff --git a/Makefile b/Makefile index 7736a78..734a62c 100644 --- a/Makefile +++ b/Makefile @@ -49,9 +49,13 @@ install: dist cp -r $(DESTDIR)/* / .PHONY: test -test: build +test: build /tmp/getopt tests/posix-compat.sh +/tmp/getopt: src/getopt.rs + $(RUSTC) --test -o /tmp/getopt src/getopt.rs + /tmp/getopt + .PHONY: rustlibs rustlibs: build/o/libsysexits.rlib build/o/libgetopt.rlib \ build/o/libstrerror.rlib diff --git a/src/getopt.rs b/src/getopt.rs index 5ce094c..dc88229 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -32,49 +32,71 @@ extern "C" { ) -> c_int; } -pub struct Opt { - pub arg: Option, - ind: *mut i32, - pub opt: String, -} - -impl Opt { - pub fn index(&self) -> usize { unsafe { *self.ind as usize } } - - pub fn set_index(&self, ind: i32) { unsafe { *self.ind = ind; } } -} - +#[derive(Clone, Debug)] pub enum OptError { MissingArg(String), UnknownOpt(String), } +#[derive(Clone, Debug)] +pub struct Opt { + arg: Option, + ind: *mut i32, + opt: Result, +} + +impl Opt { + pub fn arg(&self) -> Option { self.arg.clone() } + + /* sets optarg if default is desired */ + pub fn arg_or(&self, default: impl std::fmt::Display) -> String { + default.to_string() + } + + pub fn opt(&self) -> Result<&str, OptError> { + self.opt.as_ref().map(|o| o.as_str()).map_err(OptError::clone) + } + + /* From getopt(3p): + * + * The variable optind is the index of the next element of the argv[] + * vector to be processed. It shall be initialized to 1 by the system, and + * getopt() shall update it when it finishes with each element of argv[]. + * If the application sets optind to zero before calling getopt(), the + * behavior is unspecified. When an element of argv[] contains multiple + * option characters, it is unspecified how getopt() determines which + * options have already been processed. */ + pub fn ind(&self) -> usize { unsafe { *self.ind as usize } } + + pub fn set_ind(&self, ind: i32) { unsafe { *self.ind = ind; } } +} + /* function signature */ pub trait GetOpt { - fn getopt(&self, optstring: &str) -> Option>; + fn getopt(&self, optstring: &str) -> Option; } impl GetOpt for Vec { - fn getopt(&self, optstring: &str) -> Option> { + fn getopt(&self, optstring: &str) -> Option { let c_strings: Vec<_> = self .iter() .cloned() - .map(CString::new) - .map(Result::unwrap) + .map(|x| CString::new(x).unwrap().into_raw()) .collect(); + let boxed = Box::into_raw(c_strings.into_boxed_slice()); + let argv = boxed as *const *mut i8; + /* these operations must be separated out into separate operations so * the CStrings can live long enough */ - let argv: Vec<_> = c_strings.iter().map(|x| x.as_ptr()).collect(); - let argv_ptr = argv.as_ptr() as *const *mut c_char; let opts = CString::new(optstring).unwrap().into_raw(); let len = self.len() as c_int; unsafe { - match getopt(len, argv_ptr, opts) { + let ret = match getopt(len, argv, opts) { /* From getopt(3p): * - * The getopt() f unction shall return the next option character + * The getopt() function shall return the next option character * specified on the command line. * * A (':') shall be returned if getopt() detects a @@ -89,10 +111,24 @@ impl GetOpt for Vec { * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ 58 => { /* numerical ASCII value for ':' */ - Some(Err(OptError::MissingArg(optopt.to_string()))) + Some(Opt { + /* opt argument */ + arg: None, + /* opt index */ + ind: std::ptr::addr_of_mut!(optind), + /* error containing option */ + opt: Err(OptError::MissingArg(optopt.to_string())), + }) }, 63 => { /* numerical ASCII value for '?' */ - Some(Err(OptError::UnknownOpt(optopt.to_string()))) + Some(Opt { + /* opt argument */ + arg: None, + /* opt index */ + ind: std::ptr::addr_of_mut!(optind), + /* error containing option */ + opt: Err(OptError::UnknownOpt(optopt.to_string())), + }) }, /* From getopt(3p): * @@ -109,31 +145,56 @@ impl GetOpt for Vec { * getopt() shall return -1 after incrementing optind. */ -1 => return None, opt => { - let arg = CStr::from_ptr(optarg) - .to_string_lossy() - .into_owned(); + let arg: Option; - Some(Ok(Opt { - arg: Some(arg), /* opt argument */ - /* From getopt(3p): - * - * The variable optind is the index of the next element - * of the argv[] vector to be processed. It shall be - * initialized to 1 by the system, and getopt() shall - * update it when it finishes with each element of - * argv[]. If the application sets optind to zero - * before calling getopt(), the behavior is unspecified. - * When an element of argv[] contains multiple option - * characters, it is unspecified how getopt() - * determines which options have already been processed. - * - * This API is can be utilized with the index() and - * set_index() methods implemented for Opt. */ - ind: std::ptr::addr_of_mut!(optind), - opt: opt.to_string(), /* option itself */ - })) + if optarg.is_null() { arg = None; } + else { + arg = Some(CStr::from_ptr(optarg) + .to_string_lossy() + .into_owned()); + } + + Some(Opt { + arg, /* opt argument */ + ind: std::ptr::addr_of_mut!(optind), /* opt index */ + /* option itself */ + opt: Ok((opt as u8 as char).to_string()), + }) }, - } + }; + + /* delloc argv */ + let _ = Box::from_raw(boxed); + return ret; } } } + +#[cfg(test)] +mod tests { + use GetOpt; + + #[test] + fn testing() { + let argv: Vec = ["test", "-b", "-f", "arg", "-o", "arg"] + .iter() + .map(|s| s.to_string()) + .collect(); + + while let Some(opt) = argv.getopt(":abf:o:") { + match opt.opt() { + Ok("a") => assert_eq!(opt.ind(), 1), + Ok("b") => assert_eq!(opt.ind(), 2), + Ok("f") | Ok("o") => { + assert_eq!(opt.arg(), Some("arg".into())); + }, + _ => assert!(false), + }; + } + + if let Some(opt) = argv.getopt("abc:") { + opt.clone().set_ind(1); + assert_eq!(opt.ind(), 1); + } + } +} From e1bf49c75af4ff75aaae9761cc5a8196c4d6e198 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 22 Jun 2024 22:30:30 -0600 Subject: [PATCH 018/104] getopt.rs(3): adds comments & documentation --- src/getopt.rs | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/getopt.rs b/src/getopt.rs index dc88229..ee8cafa 100644 --- a/src/getopt.rs +++ b/src/getopt.rs @@ -40,9 +40,9 @@ pub enum OptError { #[derive(Clone, Debug)] pub struct Opt { - arg: Option, - ind: *mut i32, - opt: Result, + arg: Option, /* option argument */ + ind: *mut i32, /* option index */ + opt: Result, /* option option */ } impl Opt { @@ -53,6 +53,7 @@ impl Opt { default.to_string() } + /* makes matching the output of this method more bearable */ pub fn opt(&self) -> Result<&str, OptError> { self.opt.as_ref().map(|o| o.as_str()).map_err(OptError::clone) } @@ -68,6 +69,7 @@ impl Opt { * options have already been processed. */ pub fn ind(&self) -> usize { unsafe { *self.ind as usize } } + /* this is patently terrible and is only happening because I’m stubborn */ pub fn set_ind(&self, ind: i32) { unsafe { *self.ind = ind; } } } @@ -84,11 +86,11 @@ impl GetOpt for Vec { .map(|x| CString::new(x).unwrap().into_raw()) .collect(); + /* god knows what this does */ let boxed = Box::into_raw(c_strings.into_boxed_slice()); let argv = boxed as *const *mut i8; - /* these operations must be separated out into separate operations so - * the CStrings can live long enough */ + /* operations are separated out so that everything lives long enough */ let opts = CString::new(optstring).unwrap().into_raw(); let len = self.len() as c_int; @@ -110,21 +112,17 @@ impl GetOpt for Vec { * * Otherwise, getopt() shall return -1 when all command line * options are parsed. */ - 58 => { /* numerical ASCII value for ':' */ + 58 => { /* ASCII ':' */ Some(Opt { - /* opt argument */ arg: None, - /* opt index */ ind: std::ptr::addr_of_mut!(optind), /* error containing option */ opt: Err(OptError::MissingArg(optopt.to_string())), }) }, - 63 => { /* numerical ASCII value for '?' */ + 63 => { /* ASCII '?' */ Some(Opt { - /* opt argument */ arg: None, - /* opt index */ ind: std::ptr::addr_of_mut!(optind), /* error containing option */ opt: Err(OptError::UnknownOpt(optopt.to_string())), @@ -155,21 +153,25 @@ impl GetOpt for Vec { } Some(Opt { - arg, /* opt argument */ - ind: std::ptr::addr_of_mut!(optind), /* opt index */ - /* option itself */ + arg, + ind: std::ptr::addr_of_mut!(optind), + /* I didn’t need to cast this before; I rewrote the + * pointer logic and now I do + * + * I don’t know why this is */ opt: Ok((opt as u8 as char).to_string()), }) }, }; - /* delloc argv */ + /* delloc argv (something online said I should do this) */ let _ = Box::from_raw(boxed); return ret; } } } +/* tests (good) */ #[cfg(test)] mod tests { use GetOpt; From 6e4aeb7be7615ea899d7ba234713e50a63cc0a20 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 23 Jun 2024 01:00:48 -0600 Subject: [PATCH 019/104] fop(1): bring getopt(3) usage up-to-date --- src/fop.rs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/src/fop.rs b/src/fop.rs index 29f1522..91c8a72 100644 --- a/src/fop.rs +++ b/src/fop.rs @@ -33,25 +33,20 @@ use sysexits::{ EX_DATAERR, EX_IOERR, EX_UNAVAILABLE, EX_USAGE }; fn main() { let argv = args().collect::>(); let mut d = '\u{1E}'.to_string(); + let mut index_arg = 0; + let usage = format!( "Usage: {} [-d delimiter] index command [args...]", argv[0], ); - let mut index_arg = 0; - let mut arg_parser = Parser::new(&argv, "d:"); while let Some(opt) = argv.getopt("d:") { - match opt { - Ok(o) => { + match opt.opt() { + Ok(_) => { /* unwrap because Err(OptError::MissingArg) will be returned if - * o.arg is None */ - let arg = o.arg.clone().unwrap(); - let arg_char = arg.chars().collect::>(); - if arg_char.len() > 1 { - eprintln!("{}: {}: Not a character.", argv[0], arg); - exit(EX_USAGE); - } else { d = arg_char[0]; } - index_arg = o.index(); + * opt.arg() is None */ + d = opt.arg().unwrap(); + index_arg = opt.ind(); }, Err(_) => { eprintln!("{}", usage); From d3f5246242984a1ff03982d92adb0d2b8fb465af Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 11:36:52 -0600 Subject: [PATCH 020/104] dj(1), dj.1: remove the unnecessary -d and -q --- docs/dj.1 | 29 +++-------------------------- src/dj.c | 41 ++++++++--------------------------------- 2 files changed, 11 insertions(+), 59 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 7d28ac8..5de56eb 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -11,7 +11,7 @@ dj \(en disk jockey .SH SYNOPSIS dj -.RB ( -AdHnq ) +.RB ( -AHn ) .RB ( -a .RB [ byte ]) .RB ( -c @@ -76,18 +76,11 @@ with a null byte instead of a character. .IP \fB-c\fP Specifies a number of reads to make. The default is 0, in which case the input is read until a partial or empty read is made. -.IP \fB-d\fP -Prints invocation information before program execution as described in the -DIAGNOSTICS section. Each invocation increments the debug level of the -program. .IP \fB-H\fP Prints diagnostics messages in a human-readable manner as described in the DIAGNOSTICS section. .IP \fB-n\fP Retries failed reads once before exiting. -.IP \fB-q\fP -Suppresses error messages which print when a read or write is partial or -empty. Each invocation decrements the debug level of the program. .\" .SH STANDARD INPUT @@ -100,10 +93,8 @@ one or more of the input files is \(lq-\(rq. .\" .SH DIAGNOSTICS -On a partial or empty read, unless the -.B -q -option is specified, a diagnostic message is printed. Then, the program exits -unless the +On a partial or empty read a diagnostic message is printed. Then, the program +exits unless the .B -n option is specified. @@ -128,20 +119,6 @@ option may be specified. In this event, the following format is used instead: {ASCII line feed} .RE -If the -.B -d -option is specified, debug information will be printed at the beginning of -execution. This output contains information regarding how the program was -invoked. The following example is the result of running the program with -.B -d -as the only argument: - -.RS -argv0=dj -in= ibs=1024 skip=0 align=ff count=0 -out= obs=1024 seek=0 debug= 3 noerror=0 -.RE - In non-recoverable errors that don\(cqt pertain to the read-write cycle, a diagnostic message is printed and the program exits with the appropriate .BR sysexits.h (3) diff --git a/src/dj.c b/src/dj.c index 8a6732c..27c160a 100644 --- a/src/dj.c +++ b/src/dj.c @@ -59,14 +59,6 @@ struct Io{ /* pointer to chosen formatting */ /* (-H) */ static char *fmt_output; /* fmt_asv (default) or fmt_human (-H) */ -/* (-dq) */ static char debug; /* - * -d increments dj -qq | 0 - no diagnostic output whatsoever - * -q decrements dj -q | 1 - typical output without - * | notifications on partial reads or - * | writes - * dj | 2 - typical output (default) - * dj -d | 3 - verbose status messages */ - /* (-n) */ static char noerror; /* 0 - exits on partial reads or writes * (default) * 1 - retries on partial reads/writes @@ -84,7 +76,6 @@ static int write_flags = O_WRONLY | O_CREAT; /* dd(1). */ #define setdefaults do{ \ align = -1; \ count = 0; \ - debug = 2; \ fmt_output = fmt_asv; \ noerror = 0; \ ep[0].fl = read_flags; \ @@ -284,14 +275,13 @@ oserr(char *s){ } /* Prints statistics regarding the use of dj, particularly partially and - * completely read and written records, accessing debug, ep, and fmt_output. */ + * completely read and written records, accessing ep and fmt_output. */ static void output(void){ - if(debug >= 1) - fprintf(stderr, fmt_output, - ep[0].rec, ep[0].prec, ep[1].rec, ep[1].prec, - ep[0].bytes, ep[1].bytes); + fprintf(stderr, fmt_output, + ep[0].rec, ep[0].prec, ep[1].rec, ep[1].prec, + ep[0].bytes, ep[1].bytes); return; } @@ -342,10 +332,8 @@ int main(int argc, char *argv[]){ terminate(ep); return oserr(optarg); case 'A': align = '\0'; break; - case 'd': ++debug; break; case 'n': noerror = 1; break; case 'H': fmt_output = fmt_human; break; - case 'q': --debug; break; case 'a': if(optarg[0] != '\0' && optarg[1] == '\0'){ align = optarg[0]; @@ -367,15 +355,6 @@ int main(int argc, char *argv[]){ } } - if(debug >= 3) - fprintf(stderr, - "argv0=%s\n" - "in=%s\tibs=%d\tskip=%ld\talign=%hhx\tcount=%d\n" - "out=%s\tobs=%d\tseek=%ld\tdebug=%2d\tnoerror=%d\n", - program_name, - ep[0].fn, ep[0].bs, ep[0].seek, align, count, - ep[1].fn, ep[1].bs, ep[1].seek, debug, noerror); - if(argc > optind){ terminate(ep); return usage(); @@ -404,10 +383,8 @@ int main(int argc, char *argv[]){ break; else if(ep[0].bufuse < ep[0].bs){ ++ep[0].prec; - if(debug >= 2){ - fprintf(stderr, "%s: Partial read:\n\t", program_name); - output(); - } + fprintf(stderr, "%s: Partial read:\n\t", program_name); + output(); if(!noerror) count = 1; if(align >= 0) @@ -432,10 +409,8 @@ int main(int argc, char *argv[]){ break; }else if(c > ep[1].bufuse && ep[1].bufuse > 0){ ep[1].prec += 1; - if(debug >= 2){ - fprintf(stderr, "%s: Partial write:\n\t", program_name); - output(); - } + fprintf(stderr, "%s: Partial write:\n\t", program_name); + output(); if(!noerror) count = 1; }else if(ep[1].bufuse == 0 && c < ep[1].bs) From 95f7992e0fbdbabac78c397c357523e85c2cc576 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 11:39:34 -0600 Subject: [PATCH 021/104] dj(1): fix usage text to be consistent with man page --- src/dj.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dj.c b/src/dj.c index 27c160a..d4462e8 100644 --- a/src/dj.c +++ b/src/dj.c @@ -303,7 +303,7 @@ parse(char *s){ static int usage(void){ - fprintf(stderr, "Usage: %s (-AdfHqQ) (-a [byte]) (-c [count])\n" + fprintf(stderr, "Usage: %s (-AHn) (-a [byte]) (-c [count])\n" "\t(-i [input file]) (-b [input block size]) (-s [input offset])\n" "\t(-o [output file]) (-B [output block size]) (-S [output offset])\n", program_name); From 45a880455d440deb05034f7562cb756eae5287d7 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 12:22:33 -0600 Subject: [PATCH 022/104] dj(1): refactor to build again and to get rid of globals --- src/dj.c | 81 +++++++++++++++++++++++--------------------------------- 1 file changed, 33 insertions(+), 48 deletions(-) diff --git a/src/dj.c b/src/dj.c index d4462e8..e41f350 100644 --- a/src/dj.c +++ b/src/dj.c @@ -25,6 +25,8 @@ #include /* EX_OK, EX_USAGE */ #include /* close(2), getopt(3), lseek(2), read(2), write(2), * optarg, optind, STDIN_FILENO, STDOUT_FILENO */ +#include /* S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, + S_IWUSR */ extern int errno; /* dj uses two structures that respectively correspond to the reading and @@ -41,47 +43,17 @@ struct Io{ int prec; /* partial records processed */ int rec; /* records processed */ long seek; /* bytes to seek/skip (will be 0 after skippage) (-sS) */ -} ep[2]; /* "engineered pipe"; also "extended play", for the deejay */ +}; -/* Additionally, the following global variables are used to store user options. - */ +/* To be assigned to main:fmt_output and used with output(). */ +static char *fmt_asv = "%d\037%d\036%d\037%d\035%d\036%d\034"; +static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; -/* (-a) */ static int align; /* Only the lower 8b are used but align is - * negative if no alignment is being done. */ - -/* (-c) */ static int count; /* 0 if dj(1) runs until no more reads are - * possible. */ - -/* ASCII field separator delimited statistics */ - static char *fmt_asv = "%d\037%d\036%d\037%d\035%d\036%d\034"; -/* human-readable statistics */ - static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; -/* pointer to chosen formatting */ -/* (-H) */ static char *fmt_output; /* fmt_asv (default) or fmt_human (-H) */ - -/* (-n) */ static char noerror; /* 0 - exits on partial reads or writes - * (default) - * 1 - retries on partial reads/writes - * (-n) */ - -/* Non-configurable defaults. */ -#define bs_default 1024 /* GNU dd(1) default; twice POSIX but a neat 2^10 */ static char *program_name = ""; static char *stdin_name = ""; static char *stdout_name = ""; -static int read_flags = O_RDONLY; /* These flags are consistent with Busybox */ -static int write_flags = O_WRONLY | O_CREAT; /* dd(1). */ - -/* Macro to set defaults for user-configurable options. */ -#define setdefaults do{ \ - align = -1; \ - count = 0; \ - fmt_output = fmt_asv; \ - noerror = 0; \ - ep[0].fl = read_flags; \ - Io_setdefaults(&ep[0]); \ - ep[1].fl = write_flags; \ - Io_setdefaults(&ep[1]); }while(0) +static int read_flags = O_RDONLY; /* Consistent with Busybox dd(1). */ +static int write_flags = O_WRONLY | O_CREAT; #define MIN(a, b) (((a) < (b)) ? (a) : (b)) @@ -238,7 +210,7 @@ Io_read(struct Io *io){ static struct Io * Io_setdefaults(struct Io *io){ - io->bs = bs_default; + io->bs = 1024 /* bytes; 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ io->buf = NULL; io->bytes = 0; io->fd = (io->fl == read_flags) ? STDIN_FILENO : STDOUT_FILENO; @@ -275,13 +247,13 @@ oserr(char *s){ } /* Prints statistics regarding the use of dj, particularly partially and - * completely read and written records, accessing ep and fmt_output. */ + * completely read and written records. */ static void -output(void){ +output(struct Io io[2], char *fmt){ - fprintf(stderr, fmt_output, - ep[0].rec, ep[0].prec, ep[1].rec, ep[1].prec, - ep[0].bytes, ep[1].bytes); + fprintf(stderr, fmt, + io[0].rec, io[0].prec, io[1].rec, io[1].prec, + io[0].bytes, io[1].bytes); return; } @@ -312,14 +284,27 @@ usage(void){ } int main(int argc, char *argv[]){ + int align; /* low 8b used, negative if no alignment is being done */ + int count; /* 0 if dj(1) runs until no more reads are possible */ + struct Io ep[2]; /* "engineered pipe"; also "extended play", for the DJ */ + char *fmt_output; /* fmt_asv (default) or fmt_human (-H) */ + char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ int c; int i; - setdefaults; + /* Set defaults. */ + align = -1; + count = 0; + fmt_output = fmt_asv; + noerror = 0; + ep[0].fl = read_flags; + Io_setdefaults(&ep[0]); + ep[1].fl = write_flags; + Io_setdefaults(&ep[1]); if(argc > 0){ program_name = argv[0]; - while((c = getopt(argc, argv, "a:Ab:B:c:di:hHnqs:S:o:")) != -1) + while((c = getopt(argc, argv, "a:Ab:B:c:i:hHns:S:o:")) != -1) switch(c){ case 'i': case 'o': i = (c == 'o'); @@ -369,7 +354,7 @@ int main(int argc, char *argv[]){ }else if(ep[i].seek > 0) switch(Io_fdseek(&ep[i])){ case EX_OK: - output(); + output(ep, fmt_output); terminate(ep); return EX_OK; } @@ -384,7 +369,7 @@ int main(int argc, char *argv[]){ else if(ep[0].bufuse < ep[0].bs){ ++ep[0].prec; fprintf(stderr, "%s: Partial read:\n\t", program_name); - output(); + output(ep, fmt_output); if(!noerror) count = 1; if(align >= 0) @@ -410,7 +395,7 @@ int main(int argc, char *argv[]){ }else if(c > ep[1].bufuse && ep[1].bufuse > 0){ ep[1].prec += 1; fprintf(stderr, "%s: Partial write:\n\t", program_name); - output(); + output(ep, fmt_output); if(!noerror) count = 1; }else if(ep[1].bufuse == 0 && c < ep[1].bs) @@ -420,7 +405,7 @@ int main(int argc, char *argv[]){ }while(ep[0].bufuse > 0); }while(count == 0 || --count > 0); - output(); + output(ep, fmt_output); terminate(ep); return EX_OK; From 66f54982320eb6ca2f47da26c8dac78aaf4aaecc Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 12:40:36 -0600 Subject: [PATCH 023/104] dj(1): refactor Io_fdseek --- src/dj.c | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/dj.c b/src/dj.c index e41f350..7c0b7c3 100644 --- a/src/dj.c +++ b/src/dj.c @@ -156,18 +156,15 @@ Io_fdopen(struct Io *io, char *fn){ return fd; } -/* Seeks io->seek bytes through *io's file descriptor, (counter-intuitively) - * returning -1 if successful and a sysexits.h exit code if an unrecoverable - * error occurred. io->buf will be cleared of useful bytes and io->seek will - * be set to zero to indicate the seek occurred. */ -static int +/* Seeks io->seek bytes through *io's file descriptor, subtracting the number + * of sought bytes from io->seek. This procedure leaves garbage in io->buf. */ +static void Io_fdseek(struct Io *io){ - int (*op)(int, void *, size_t); - if(!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1) - return -1; + if(io->seek != 0 + || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)) + return; - /* repeated code to get the condition out of the loop */ if(io->fl == write_flags){ memset(io->buf, '\0', io->bs); /* We're going to cheat and use bufuse as the retval for write(2), @@ -186,12 +183,11 @@ Io_fdseek(struct Io *io){ /* second chance */ io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek)); }while((io->seek -= io->bufuse) > 0 && io->bufuse != 0); - }else - return EX_SOFTWARE; + } io->bufuse = 0; - return -1; + return; } /* Reads io->bs bytes from *io's file descriptor into io->buf, storing the @@ -352,11 +348,10 @@ int main(int argc, char *argv[]){ terminate(ep); return EX_OSERR; }else if(ep[i].seek > 0) - switch(Io_fdseek(&ep[i])){ - case EX_OK: - output(ep, fmt_output); + Io_fdseek(&ep[i]); + if(ep[i].seek > 0){ terminate(ep); - return EX_OK; + return oserr(ep[i].fn); } } From b70b356ce5ec6a78f029a8db0df6b5a3d3944827 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 12:45:50 -0600 Subject: [PATCH 024/104] dj(1): remove Io_buffree --- src/dj.c | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/dj.c b/src/dj.c index 7c0b7c3..01832a8 100644 --- a/src/dj.c +++ b/src/dj.c @@ -67,8 +67,8 @@ static int write_flags = O_WRONLY | O_CREAT; * particular io[2] used in main. Error conditions are not checked because this * is only used when the program is about to terminate (hence its name). */ #define terminate(io) do{ \ - Io_buffree(&(io)[0]); \ - Io_buffree(&(io)[1]); \ + free((io[0]).buf); \ + free((io[1]).buf); \ Io_fdclose(&(io)[0]); \ Io_fdclose(&(io)[1]); }while(0) @@ -79,15 +79,6 @@ Io_bufalloc(struct Io *io){ return (io->buf = malloc(io->bs * (sizeof *io->buf))); } -/* Frees *io's buffer. Returns io. */ -static struct Io * -Io_buffree(struct Io *io){ - - free(io->buf); - - return io; -} - /* Fills the unused portion of io's buffer with padding, updating io->bufuse. * Returns io. */ static struct Io * From e65f6b650df5323d66ec94e3b8fe5b792f6e5fb5 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 13:41:24 -0600 Subject: [PATCH 025/104] dj(1): more refactor (get rid of ep pun) --- src/dj.c | 101 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 52 insertions(+), 49 deletions(-) diff --git a/src/dj.c b/src/dj.c index 01832a8..af842a4 100644 --- a/src/dj.c +++ b/src/dj.c @@ -156,6 +156,9 @@ Io_fdseek(struct Io *io){ || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)) return; + if(io->fl == write_flags) + memset(io->buf, '\0', io->bs); + if(io->fl == write_flags){ memset(io->buf, '\0', io->bs); /* We're going to cheat and use bufuse as the retval for write(2), @@ -273,7 +276,7 @@ usage(void){ int main(int argc, char *argv[]){ int align; /* low 8b used, negative if no alignment is being done */ int count; /* 0 if dj(1) runs until no more reads are possible */ - struct Io ep[2]; /* "engineered pipe"; also "extended play", for the DJ */ + struct Io io[2]; char *fmt_output; /* fmt_asv (default) or fmt_human (-H) */ char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ int c; @@ -284,10 +287,10 @@ int main(int argc, char *argv[]){ count = 0; fmt_output = fmt_asv; noerror = 0; - ep[0].fl = read_flags; - Io_setdefaults(&ep[0]); - ep[1].fl = write_flags; - Io_setdefaults(&ep[1]); + io[0].fl = read_flags; + Io_setdefaults(&io[0]); + io[1].fl = write_flags; + Io_setdefaults(&io[1]); if(argc > 0){ program_name = argv[0]; @@ -296,12 +299,12 @@ int main(int argc, char *argv[]){ case 'i': case 'o': i = (c == 'o'); if(optarg[0] == '-' && optarg[1] == '\0'){ /* optarg == "-" */ - ep[i].fd = (i == 0) ? STDIN_FILENO : STDOUT_FILENO; - ep[i].fn = (i == 0) ? stdin_name : stdout_name; + io[i].fd = (i == 0) ? STDIN_FILENO : STDOUT_FILENO; + io[i].fn = (i == 0) ? stdin_name : stdout_name; break; - }else if(Io_fdopen(&ep[i], optarg) != -1) + }else if(Io_fdopen(&io[i], optarg) != -1) break; - terminate(ep); + terminate(io); return oserr(optarg); case 'A': align = '\0'; break; case 'n': noerror = 1; break; @@ -317,82 +320,82 @@ int main(int argc, char *argv[]){ break; i = isupper(c); c = tolower(c); - if((c == 'b' && (ep[i].bs = parse(optarg)) > 0) - || (c == 's' && (ep[i].seek = parse(optarg)) >= 0)) + if((c == 'b' && (io[i].bs = parse(optarg)) > 0) + || (c == 's' && (io[i].seek = parse(optarg)) >= 0)) break; /* FALLTHROUGH */ default: - terminate(ep); + terminate(io); return usage(); } } if(argc > optind){ - terminate(ep); + terminate(io); return usage(); } - for(i = 0; i <= 1; ++i){ - if(Io_bufalloc(&ep[i]) == NULL){ + for(i = 0; i < 2; ++i){ + if(Io_bufalloc(&io[i]) == NULL){ fprintf(stderr, "%s: Failed to allocate %d bytes\n", - program_name, ep[i].bs); - terminate(ep); + program_name, io[i].bs); + terminate(io); return EX_OSERR; - }else if(ep[i].seek > 0) - Io_fdseek(&ep[i]); - if(ep[i].seek > 0){ - terminate(ep); - return oserr(ep[i].fn); + }else if(io[i].seek > 0) + Io_fdseek(&io[i]); + if(io[i].seek > 0){ + terminate(io); + return oserr(io[i].fn); } } do{ /* read */ - Io_read(&ep[0]); - if(!noerror && ep[0].bufuse == 0) - Io_read(&ep[0]); /* second chance */ - if(ep[0].bufuse == 0) /* that's all she wrote */ + Io_read(&io[0]); + if(!noerror && io[0].bufuse == 0) + Io_read(&io[0]); /* second chance */ + if(io[0].bufuse == 0) /* that's all she wrote */ break; - else if(ep[0].bufuse < ep[0].bs){ - ++ep[0].prec; + else if(io[0].bufuse < io[0].bs){ + ++io[0].prec; fprintf(stderr, "%s: Partial read:\n\t", program_name); - output(ep, fmt_output); + output(io, fmt_output); if(!noerror) count = 1; if(align >= 0) - Io_bufrpad(&ep[0], align); + Io_bufrpad(&io[0], align); }else - ++ep[0].rec; + ++io[0].rec; /* write */ - do{ if(ep[1].bs > ep[0].bs){ /* io[1].bs > io[0].bs */ - Io_bufxapp(&ep[1], &ep[0]); - if(ep[0].bs + ep[1].bufuse <= ep[1].bs && count != 1) + do{ if(io[1].bs > io[0].bs){ /* io[1].bs > io[0].bs */ + Io_bufxapp(&io[1], &io[0]); + if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) continue; /* we could write more */ }else - Io_bufxfer(&ep[1], &ep[0], MIN(ep[0].bufuse, ep[1].bs)); + Io_bufxfer(&io[1], &io[0], MIN(io[0].bufuse, io[1].bs)); - c = ep[1].bufuse; - Io_write(&ep[1]); - if(!noerror && ep[1].bufuse == c) - Io_write(&ep[1]); /* second chance */ - if(c == ep[1].bufuse){ /* no more love */ + c = io[1].bufuse; + Io_write(&io[1]); + if(!noerror && io[1].bufuse == c) + Io_write(&io[1]); /* second chance */ + if(c == io[1].bufuse){ /* no more love */ count = 1; break; - }else if(c > ep[1].bufuse && ep[1].bufuse > 0){ - ep[1].prec += 1; + }else if(c > io[1].bufuse && io[1].bufuse > 0){ + io[1].prec += 1; fprintf(stderr, "%s: Partial write:\n\t", program_name); - output(ep, fmt_output); + output(io, fmt_output); if(!noerror) count = 1; - }else if(ep[1].bufuse == 0 && c < ep[1].bs) - ++ep[1].prec; + }else if(io[1].bufuse == 0 && c < io[1].bs) + ++io[1].prec; else - ++ep[1].rec; - }while(ep[0].bufuse > 0); + ++io[1].rec; + }while(io[0].bufuse > 0); }while(count == 0 || --count > 0); - output(ep, fmt_output); - terminate(ep); + output(io, fmt_output); + terminate(io); return EX_OK; } From fb74e7bef036d266b34fc93621d6889bfa31b61d Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 13:45:36 -0600 Subject: [PATCH 026/104] dj(1), dj.1: Remove -A (use -a "\0") (see #101) --- docs/dj.1 | 10 +++------- src/dj.c | 7 +++---- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 5de56eb..1494827 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -11,7 +11,7 @@ dj \(en disk jockey .SH SYNOPSIS dj -.RB ( -AHn ) +.RB ( -Hn ) .RB ( -a .RB [ byte ]) .RB ( -c @@ -67,12 +67,8 @@ Seeks a number of bytes through the output before starting to write from the input. If the output is a stream, null characters are printed. .IP \fB-a\fP Accepts a single literal byte with which the input buffer is padded in the event -of an incomplete read from the input file. -.IP \fB-A\fP -Specifying this option pads the input buffer with null bytes in the event of an -incomplete read. This is equivalent to specifying -.B -a -with a null byte instead of a character. +of an incomplete read from the input file. If the option argument is empty, the +null byte is used. .IP \fB-c\fP Specifies a number of reads to make. The default is 0, in which case the input is read until a partial or empty read is made. diff --git a/src/dj.c b/src/dj.c index af842a4..b45513e 100644 --- a/src/dj.c +++ b/src/dj.c @@ -265,7 +265,7 @@ parse(char *s){ static int usage(void){ - fprintf(stderr, "Usage: %s (-AHn) (-a [byte]) (-c [count])\n" + fprintf(stderr, "Usage: %s (-Hn) (-a [byte]) (-c [count])\n" "\t(-i [input file]) (-b [input block size]) (-s [input offset])\n" "\t(-o [output file]) (-B [output block size]) (-S [output offset])\n", program_name); @@ -294,7 +294,7 @@ int main(int argc, char *argv[]){ if(argc > 0){ program_name = argv[0]; - while((c = getopt(argc, argv, "a:Ab:B:c:i:hHns:S:o:")) != -1) + while((c = getopt(argc, argv, "a:b:B:c:i:hHns:S:o:")) != -1) switch(c){ case 'i': case 'o': i = (c == 'o'); @@ -306,11 +306,10 @@ int main(int argc, char *argv[]){ break; terminate(io); return oserr(optarg); - case 'A': align = '\0'; break; case 'n': noerror = 1; break; case 'H': fmt_output = fmt_human; break; case 'a': - if(optarg[0] != '\0' && optarg[1] == '\0'){ + if(optarg[0] == '\0' || optarg[1] == '\0'){ align = optarg[0]; break; } From 2cfae0e8d7595964a492bf03f601512f0c7d15be Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 15:15:37 -0600 Subject: [PATCH 027/104] dj(1): refactor (remove Io_setdefaults and other stuff) --- src/dj.c | 66 ++++++++++++++++++++++++-------------------------------- 1 file changed, 28 insertions(+), 38 deletions(-) diff --git a/src/dj.c b/src/dj.c index b45513e..5632645 100644 --- a/src/dj.c +++ b/src/dj.c @@ -16,7 +16,6 @@ * along with this program. If not, see https://www.gnu.org/licenses/. */ -#include /* isupper(3), tolower(3) */ #include /* errno */ #include /* open(2) */ #include /* fprintf(3), stderr */ @@ -29,6 +28,8 @@ S_IWUSR */ extern int errno; +char *program_name = "dj"; + /* dj uses two structures that respectively correspond to the reading and * writing ends of its jockeyed "pipe". User-configurable members are noted * with their relevant options. */ @@ -49,9 +50,9 @@ struct Io{ static char *fmt_asv = "%d\037%d\036%d\037%d\035%d\036%d\034"; static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; -static char *program_name = ""; static char *stdin_name = ""; static char *stdout_name = ""; + static int read_flags = O_RDONLY; /* Consistent with Busybox dd(1). */ static int write_flags = O_WRONLY | O_CREAT; @@ -195,23 +196,6 @@ Io_read(struct Io *io){ return io; } -/* Sets the variables in a struct *io to the defaults. Identifies the read/ - * write ends of the "pipe" by checking io->fl. Returns io. */ -static struct Io * -Io_setdefaults(struct Io *io){ - - io->bs = 1024 /* bytes; 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ - io->buf = NULL; - io->bytes = 0; - io->fd = (io->fl == read_flags) ? STDIN_FILENO : STDOUT_FILENO; - io->fn = (io->fl == read_flags) ? stdin_name : stdout_name; - io->prec = 0; - io->rec = 0; - io->seek = 0; - - return io; -} - /* Writes io->bufuse units from io->buf to io->fd, permuting any unwritten * bytes to the start of io->buf and updating io->bufuse. If io->bufuse doesn't * change, errno will probably be set. Returns io. */ @@ -263,12 +247,12 @@ parse(char *s){ } static int -usage(void){ +usage(char *s){ fprintf(stderr, "Usage: %s (-Hn) (-a [byte]) (-c [count])\n" "\t(-i [input file]) (-b [input block size]) (-s [input offset])\n" "\t(-o [output file]) (-B [output block size]) (-S [output offset])\n", - program_name); + s); return EX_USAGE; } @@ -276,31 +260,37 @@ usage(void){ int main(int argc, char *argv[]){ int align; /* low 8b used, negative if no alignment is being done */ int count; /* 0 if dj(1) runs until no more reads are possible */ + char *fmt_output; /* == fmt_asv (default) or fmt_human (-H) */ + size_t i; /* side of io being modified */ struct Io io[2]; - char *fmt_output; /* fmt_asv (default) or fmt_human (-H) */ char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ - int c; - int i; /* Set defaults. */ align = -1; count = 0; fmt_output = fmt_asv; noerror = 0; - io[0].fl = read_flags; - Io_setdefaults(&io[0]); - io[1].fl = write_flags; - Io_setdefaults(&io[1]); + for(i = 0; i < 2; ++i){ + io[i].bs = 1024 /* 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ + io[i].bytes = 0; + io[i].fd = i ? STDIN_FILENO : STDOUT_FILENO; + io[i].fn = i ? stdin_name : stdout_name; + io[i].fl = i ? read_flags : write_flags; + io[i].prec = 0; + io[i].rec = 0; + io[i].seek = 0; + } if(argc > 0){ + int c; + program_name = argv[0]; while((c = getopt(argc, argv, "a:b:B:c:i:hHns:S:o:")) != -1) switch(c){ - case 'i': case 'o': - i = (c == 'o'); + case 'i': case 'o': i = (c == 'o') if(optarg[0] == '-' && optarg[1] == '\0'){ /* optarg == "-" */ - io[i].fd = (i == 0) ? STDIN_FILENO : STDOUT_FILENO; - io[i].fn = (i == 0) ? stdin_name : stdout_name; + io[i].fd = i ? STDIN_FILENO : STDOUT_FILENO; + io[i].fn = i ? stdin_name : stdout_name; break; }else if(Io_fdopen(&io[i], optarg) != -1) break; @@ -314,24 +304,24 @@ int main(int argc, char *argv[]){ break; } /* FALLTHROUGH */ - case 'c': case 'b': case 's': case 'B': case 'S': + case 'c': case 'b': case 's': case 'B': case 'S': /* numbers */ if(c == 'c' && (count = parse(optarg)) >= 0) break; - i = isupper(c); - c = tolower(c); + i = (c >= 'A' && c <= 'Z'); /* uppercase changes output */ + c &= 0x20 /* 0b 0010 0000 */; /* (ASCII) make lowercase */ if((c == 'b' && (io[i].bs = parse(optarg)) > 0) || (c == 's' && (io[i].seek = parse(optarg)) >= 0)) break; /* FALLTHROUGH */ default: terminate(io); - return usage(); + return usage(program_name); } } if(argc > optind){ terminate(io); - return usage(); + return usage(program_name); } for(i = 0; i < 2; ++i){ @@ -366,7 +356,7 @@ int main(int argc, char *argv[]){ ++io[0].rec; /* write */ - do{ if(io[1].bs > io[0].bs){ /* io[1].bs > io[0].bs */ + do{ if(io[1].bs > io[0].bs){ Io_bufxapp(&io[1], &io[0]); if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) continue; /* we could write more */ From 3a66022c6d735a3def3e52f4883178dfafe6d24f Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 26 Jun 2024 15:28:02 -0600 Subject: [PATCH 028/104] dj(1): more refactor (get rid of the c scratch variable, use scoping) --- src/dj.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/dj.c b/src/dj.c index 5632645..a9e7cdf 100644 --- a/src/dj.c +++ b/src/dj.c @@ -287,7 +287,7 @@ int main(int argc, char *argv[]){ program_name = argv[0]; while((c = getopt(argc, argv, "a:b:B:c:i:hHns:S:o:")) != -1) switch(c){ - case 'i': case 'o': i = (c == 'o') + case 'i': case 'o': i = (c == 'o'); if(optarg[0] == '-' && optarg[1] == '\0'){ /* optarg == "-" */ io[i].fd = i ? STDIN_FILENO : STDOUT_FILENO; io[i].fn = i ? stdin_name : stdout_name; @@ -356,27 +356,30 @@ int main(int argc, char *argv[]){ ++io[0].rec; /* write */ - do{ if(io[1].bs > io[0].bs){ + do{ + int t; + + if(io[1].bs > io[0].bs){ Io_bufxapp(&io[1], &io[0]); if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) continue; /* we could write more */ }else Io_bufxfer(&io[1], &io[0], MIN(io[0].bufuse, io[1].bs)); - c = io[1].bufuse; + t = io[1].bufuse; Io_write(&io[1]); - if(!noerror && io[1].bufuse == c) + if(!noerror && io[1].bufuse == t) Io_write(&io[1]); /* second chance */ - if(c == io[1].bufuse){ /* no more love */ + if(t == io[1].bufuse){ /* no more love */ count = 1; break; - }else if(c > io[1].bufuse && io[1].bufuse > 0){ + }else if(t > io[1].bufuse && io[1].bufuse > 0){ io[1].prec += 1; fprintf(stderr, "%s: Partial write:\n\t", program_name); output(io, fmt_output); if(!noerror) count = 1; - }else if(io[1].bufuse == 0 && c < io[1].bs) + }else if(io[1].bufuse == 0 && t < io[1].bs) ++io[1].prec; else ++io[1].rec; From 2f87ad948f530f095b5821a9e60f4cd857df6a4e Mon Sep 17 00:00:00 2001 From: emma Date: Thu, 27 Jun 2024 14:04:31 -0600 Subject: [PATCH 029/104] strerror.rs(3), getopt.rs(3): renames --- Makefile | 14 +++++++------- src/{getopt.rs => libgetopt.rs} | 0 src/{strerror.rs => libstrerror.rs} | 0 3 files changed, 7 insertions(+), 7 deletions(-) rename src/{getopt.rs => libgetopt.rs} (100%) rename src/{strerror.rs => libstrerror.rs} (100%) diff --git a/Makefile b/Makefile index 2188b41..8109cd6 100644 --- a/Makefile +++ b/Makefile @@ -51,23 +51,23 @@ install: dist .PHONY: test test: build /tmp/getopt + /tmp/getopt tests/posix-compat.sh -/tmp/getopt: src/getopt.rs - $(RUSTC) --test -o /tmp/getopt src/getopt.rs - /tmp/getopt +/tmp/getopt: src/libgetopt.rs + $(RUSTC) --test -o /tmp/getopt src/libgetopt.rs .PHONY: rustlibs rustlibs: build/o/libsysexits.rlib build/o/libgetopt.rlib \ build/o/libstrerror.rlib -build/o/libgetopt.rlib: build src/getopt.rs +build/o/libgetopt.rlib: build src/libgetopt.rs $(RUSTC) $(RUSTFLAGS) --crate-type=lib --crate-name=getopt \ - -o $@ src/getopt.rs + -o $@ src/libgetopt.rs -build/o/libstrerror.rlib: build src/strerror.rs +build/o/libstrerror.rlib: build src/libstrerror.rs $(RUSTC) $(RUSTFLAGS) --crate-type=lib -o $@ \ - src/strerror.rs + src/libstrerror.rs # bandage solution until bindgen(1) gets stdin support build/o/libsysexits.rlib: build $(SYSEXITS)sysexits.h diff --git a/src/getopt.rs b/src/libgetopt.rs similarity index 100% rename from src/getopt.rs rename to src/libgetopt.rs diff --git a/src/strerror.rs b/src/libstrerror.rs similarity index 100% rename from src/strerror.rs rename to src/libstrerror.rs From d07bb7da416b7bbefaae1d9df7402e27a319fc80 Mon Sep 17 00:00:00 2001 From: DTB Date: Fri, 28 Jun 2024 08:33:31 -0600 Subject: [PATCH 030/104] swab(1): untested move to new getopt bindings --- src/swab.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/src/swab.rs b/src/swab.rs index ca944d9..d997ddf 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -49,20 +49,16 @@ fn main() -> ExitCode { let mut force = false; let mut wordsize: usize = 2; - loop { - match opts.next() { - None => break, - Some(opt) => - match opt { - Ok(Opt('f', None)) => force = true, - Ok(Opt('w', Some(arg))) => { - match arg.parse::() { - Ok(w) if w % 2 == 0 => { wordsize = w; () }, - _ => { return usage(&argv[0]); }, - } - }, - _ => { return usage(&argv[0]); } - } + while let Some(opt) = argv.getopt("fw:") { + match opt.opt() { + Ok("f") => force = true, + Ok("w") => { + match arg.parse::() { + Ok(w) if w % 2 == 0 => { wordsize = w; () }, + _ => { return usage(&argv[0]); }, + } + }, + _ => { return usage(&argv[0]); } } } From 50bbee10a9b7403893dd64ae527fb852a70edfab Mon Sep 17 00:00:00 2001 From: emma Date: Fri, 28 Jun 2024 10:22:20 -0600 Subject: [PATCH 031/104] libgetopt.rs(3): fixes typecasting for ARM devices --- src/libgetopt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libgetopt.rs b/src/libgetopt.rs index ee8cafa..8064c81 100644 --- a/src/libgetopt.rs +++ b/src/libgetopt.rs @@ -88,7 +88,7 @@ impl GetOpt for Vec { /* god knows what this does */ let boxed = Box::into_raw(c_strings.into_boxed_slice()); - let argv = boxed as *const *mut i8; + let argv = boxed as *const *mut c_char; /* operations are separated out so that everything lives long enough */ let opts = CString::new(optstring).unwrap().into_raw(); From e341c38cd63941e65ee32a91c9c9c653d4b761fb Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 05:18:20 -0600 Subject: [PATCH 032/104] docs, src: updates usage text for utilities --- docs/dj.1 | 26 +++++++++----------------- docs/intcmp.1 | 4 +--- docs/mm.1 | 8 +++----- docs/npc.1 | 2 +- docs/scrut.1 | 4 ++-- docs/str.1 | 3 +-- docs/strcmp.1 | 3 +-- docs/swab.1 | 14 +++++--------- src/dj.c | 6 +++--- src/intcmp.c | 2 +- src/mm.c | 2 +- src/npc.c | 2 +- src/scrut.c | 2 +- src/str.c | 2 +- src/strcmp.c | 2 +- src/swab.rs | 2 +- 16 files changed, 33 insertions(+), 51 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 7031ccf..4b0b5b1 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -11,25 +11,17 @@ dj \(en disk jockey .SH SYNOPSIS dj -.RB ( -AdHnq ) -.RB ( -a -.RB [ byte ]) -.RB ( -c -.RB [ count ]) +.RB [ -AdHnq ] +.RB [ -a\ byte ] +.RB [ -c\ count ] -.RB ( -i -[\fBinput file\fP]) -.RB ( -b -[\fBinput block size\fP]) -.RB ( -s -[\fBinput offset\fP]) +.RB [ -i\ input_file ] +.RB [ -b\ input_block_size ] +.RB [ -s\ input_offset ] -.RB ( -o -[\fBoutput file\fP]) -.RB ( -B -[\fBoutput block size\fP]) -.RB ( -S -[\fBoutput offset\fP]) +.RB [ -o\ output_file ] +.RB [ -B\ output_block_size ] +.RB [ -S\ output_offset ] .\" .SH DESCRIPTION diff --git a/docs/intcmp.1 b/docs/intcmp.1 index 034a4fd..b90f23a 100644 --- a/docs/intcmp.1 +++ b/docs/intcmp.1 @@ -11,9 +11,7 @@ intcmp \(en compare integers .SH SYNOPSIS intcmp -.RB ( -egl ) -.RB [ integer ] -.RB [ integer... ] +.RB [ -egl ]\ integer\ integer... .SH DESCRIPTION Compare integers to each other. .\" diff --git a/docs/mm.1 b/docs/mm.1 index 2ff9f44..735f9df 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -10,11 +10,9 @@ mm \(en middleman .SH SYNOPSIS mm -.RB ( -aenu ) -.RB ( -i -.RB [ input ]) -.RB ( -o -.RB [ output ]) +.RB [ -aenu ] +.RB [ -i\ input ] +.RB [ -o\ output ] .\" .SH DESCRIPTION diff --git a/docs/npc.1 b/docs/npc.1 index 3e7af39..5acee9e 100644 --- a/docs/npc.1 +++ b/docs/npc.1 @@ -11,7 +11,7 @@ npc \(en show non-printing characters .SH SYNOPSIS npc -.RB ( -et ) +.RB [ -et ] .\" .SH DESCRIPTION diff --git a/docs/scrut.1 b/docs/scrut.1 index 56383b8..2b95bee 100644 --- a/docs/scrut.1 +++ b/docs/scrut.1 @@ -10,8 +10,8 @@ scrut \(en scrutinize file properties .SH SYNOPSIS scrut -.RB ( -LSbcdefgkprsuwx ) -.RB [ file... ] +.RB [ -LSbcdefgkprsuwx ] +.B file... .\" .SH DESCRIPTION diff --git a/docs/str.1 b/docs/str.1 index 22ffea1..1a4d8e4 100644 --- a/docs/str.1 +++ b/docs/str.1 @@ -11,8 +11,7 @@ str \(en test string arguments .SH SYNOPSIS str -.RB [ type ] -.RB [ string... ] +.B type string... .\" .SH DESCRIPTION diff --git a/docs/strcmp.1 b/docs/strcmp.1 index 0ad21b2..c99c8c8 100644 --- a/docs/strcmp.1 +++ b/docs/strcmp.1 @@ -11,8 +11,7 @@ strcmp \(en compare strings .SH SYNOPSIS strcmp -.RM [ string ] -.RB [ strings... ] +.B string string... .\" .SH DESCRIPTION diff --git a/docs/swab.1 b/docs/swab.1 index 72f0f19..e589c10 100644 --- a/docs/swab.1 +++ b/docs/swab.1 @@ -11,11 +11,8 @@ swab \(en swap bytes .SH SYNOPSIS swab -.RB ( -f ) -.RB ( -w -.R [ -.B word size -.R ]) +.RB [ -f ] +.RB [ -w\ word_size ] .\" .SH DESCRIPTION @@ -26,10 +23,9 @@ Swap the latter and former halves of a block of bytes. .IP \fB-f\fP Ignore SIGINT signal. .IP \fB-w\fP -Configures the word size; that is, the size in bytes of the block size -on which to operate. The default word size is 2. The word size must be -cleanly divisible by 2, otherwise the block of bytes being processed can\(cqt be -halved. +Configures the word size; that is, the size in bytes of the block size on which +to operate. The default word size is 2. The word size must be cleanly divisible +by 2, otherwise the block of bytes being processed can\(cqt be halved. .\" .SH EXAMPLES diff --git a/src/dj.c b/src/dj.c index 8a6732c..3885012 100644 --- a/src/dj.c +++ b/src/dj.c @@ -313,9 +313,9 @@ parse(char *s){ static int usage(void){ - fprintf(stderr, "Usage: %s (-AdfHqQ) (-a [byte]) (-c [count])\n" - "\t(-i [input file]) (-b [input block size]) (-s [input offset])\n" - "\t(-o [output file]) (-B [output block size]) (-S [output offset])\n", + fprintf(stderr, "Usage: %s [-AdfHqQ] [-a byte] [-c count]\n" + "\t[-i input_file] [-b input_block_size] [-s input_offset]\n" + "\t[-o output_file] [-B output_block_size] [-S output_offset]\n", program_name); return EX_USAGE; diff --git a/src/intcmp.c b/src/intcmp.c index 408474b..1fd278d 100644 --- a/src/intcmp.c +++ b/src/intcmp.c @@ -52,7 +52,7 @@ int main(int argc, char *argv[]){ if(optind + 2 /* ref cmp */ > argc){ usage: fprintf(stderr, - "Usage: %s (-eghl) [integer] [integer...]\n", + "Usage: %s [-eghl] integer integer...\n", argv[0] == NULL ? program_name : argv[0]); return EX_USAGE; } diff --git a/src/mm.c b/src/mm.c index dc337b7..e905b35 100644 --- a/src/mm.c +++ b/src/mm.c @@ -110,7 +110,7 @@ oserr(char *s, char *r){ * returns an exit status appropriate for a usage error. */ int usage(char *s){ - fprintf(stderr, "Usage: %s (-aenu) (-i [input])... (-o [output])...\n", s); + fprintf(stderr, "Usage: %s [-aenu] [-i input]... [-o output]...\n", s); return EX_USAGE; } diff --git a/src/npc.c b/src/npc.c index 8b97180..6b5e5f0 100644 --- a/src/npc.c +++ b/src/npc.c @@ -39,7 +39,7 @@ int main(int argc, char *argv[]){ } if(argc > optind){ -usage: fprintf(stderr, "Usage: %s (-eht)\n", argv[0]); +usage: fprintf(stderr, "Usage: %s [-eht]\n", argv[0]); return EX_USAGE; } diff --git a/src/scrut.c b/src/scrut.c index c5b675f..d85d243 100644 --- a/src/scrut.c +++ b/src/scrut.c @@ -66,7 +66,7 @@ int main(int argc, char *argv[]){ if(ops[i] == 'e') continue; else if(ops[i] == 'h'){ -usage: fprintf(stderr, "Usage: %s (-%s) [file...]\n", +usage: fprintf(stderr, "Usage: %s [-%s] file...\n", argv[0] == NULL ? program_name : argv[0], diff --git a/src/str.c b/src/str.c index ae03b1d..b4725eb 100644 --- a/src/str.c +++ b/src/str.c @@ -56,7 +56,7 @@ int main(int argc, char *argv[]){ goto pass; } - fprintf(stderr, "Usage: %s [type] [string...]\n", + fprintf(stderr, "Usage: %s type string...\n", argv[0] == NULL ? program_name : argv[0]); return EX_USAGE; diff --git a/src/strcmp.c b/src/strcmp.c index acb4946..33b73c2 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -8,7 +8,7 @@ int main(int argc, char *argv[]){ int i; if(argc < 3){ - fprintf(stderr, "Usage: %s [string] [string...]\n", + fprintf(stderr, "Usage: %s string string...\n", argv[0] == NULL ? program_name : argv[0]); return EX_USAGE; } diff --git a/src/swab.rs b/src/swab.rs index ca944d9..471f92b 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -35,7 +35,7 @@ fn oserr(s: &str, e: Error) -> ExitCode { } fn usage(s: &str) -> ExitCode { - eprintln!("Usage: {} (-f) (-w [wordsize])", s); + eprintln!("Usage: {} [-f] [-w word_size]", s); ExitCode::from(EX_USAGE as u8) } From 07a12ba81c29e06775eb129a187a4db358cac4a2 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 05:28:23 -0600 Subject: [PATCH 033/104] docs, src: fixing man page and usage text readability --- docs/dj.1 | 28 ++++++++++++++-------------- docs/fop.1 | 2 +- docs/mm.1 | 4 ++-- docs/swab.1 | 2 +- src/dj.c | 4 ++-- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 4b0b5b1..43c2750 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -15,13 +15,13 @@ dj .RB [ -a\ byte ] .RB [ -c\ count ] -.RB [ -i\ input_file ] -.RB [ -b\ input_block_size ] -.RB [ -s\ input_offset ] +.RB [ -i\ file ] +.RB [ -b\ block_size ] +.RB [ -s\ offset ] -.RB [ -o\ output_file ] -.RB [ -B\ output_block_size ] -.RB [ -S\ output_offset ] +.RB [ -o\ file ] +.RB [ -B\ block_size ] +.RB [ -S\ offset ] .\" .SH DESCRIPTION @@ -39,25 +39,25 @@ immediately subsequent to the specified byte. .\" .SH OPTIONS -.IP \fB-i\fP +.IP \fB-i\fP\ \fIfile\fP Takes a file path as an argument and opens it for use as an input. -.IP \fB-b\fP +.IP \fB-b\fP\ \fIblock_size\fP Takes a numeric argument as the size in bytes of the input buffer, the default being 1024. -.IP \fB-s\fP +.IP \fB-s\fP\ \fIoffset\fP Takes a numeric argument as the number of bytes to skip into the input before starting to read. If the standard input is used, bytes read to this point are discarded. -.IP \fB-o\fP +.IP \fB-o\fP\ \fIfile\fP Takes a file path as an argument and opens it for use as an output. -.IP \fB-B\fP +.IP \fB-B\fP\ \fIblock_size\fP Does the same as .B -b but for the output buffer. -.IP \fB-S\fP +.IP \fB-S\fP\ \fIoffset\fP Seeks a number of bytes through the output before starting to write from the input. If the output is a stream, null characters are printed. -.IP \fB-a\fP +.IP \fB-a\fP\ \fIbyte\fP Accepts a single literal byte with which the input buffer is padded in the event of an incomplete read from the input file. .IP \fB-A\fP @@ -65,7 +65,7 @@ Specifying this option pads the input buffer with null bytes in the event of an incomplete read. This is equivalent to specifying .B -a with a null byte instead of a character. -.IP \fB-c\fP +.IP \fB-c\fP\ \fIcount\fP Specifies a number of reads to make. The default is 0, in which case the input is read until a partial or empty read is made. .IP \fB-d\fP diff --git a/docs/fop.1 b/docs/fop.1 index d777c68..b96033a 100644 --- a/docs/fop.1 +++ b/docs/fop.1 @@ -22,7 +22,7 @@ Performs operations on specified fields in data read from the standard input. .\" .SH OPTIONS -.IP \fB-d\fP +.IP \fB-d\fP\ \fIdelimiter\fP Sets a delimiter by which the input data will be split into fields. The default is an ASCII record separator. .\" diff --git a/docs/mm.1 b/docs/mm.1 index 735f9df..2916aa7 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -24,10 +24,10 @@ Catenate input files and write them to the start of each output file or stream. Opens subsequent outputs for appending rather than updating. .IP \fB-e\fP Use the standard error as an output. -.IP \fB-i\fP +.IP \fB-i\fP\ \fIinput\fP Opens a path as an input. If one or more of the input files is \(lq-\(rq or if no inputs are specified, the standard input shall be used. -.IP \fB-o\fP +.IP \fB-o\fP\ \fIoutput\fP Opens a path as an output. If one or more of the output files is \(lq-\(rq or if no outputs are specified, the standard output shall be used. .IP \fB-u\fP diff --git a/docs/swab.1 b/docs/swab.1 index e589c10..42eef95 100644 --- a/docs/swab.1 +++ b/docs/swab.1 @@ -22,7 +22,7 @@ Swap the latter and former halves of a block of bytes. .IP \fB-f\fP Ignore SIGINT signal. -.IP \fB-w\fP +.IP \fB-w\fP\ \fIword_size\fP Configures the word size; that is, the size in bytes of the block size on which to operate. The default word size is 2. The word size must be cleanly divisible by 2, otherwise the block of bytes being processed can\(cqt be halved. diff --git a/src/dj.c b/src/dj.c index 3885012..beafde8 100644 --- a/src/dj.c +++ b/src/dj.c @@ -314,8 +314,8 @@ static int usage(void){ fprintf(stderr, "Usage: %s [-AdfHqQ] [-a byte] [-c count]\n" - "\t[-i input_file] [-b input_block_size] [-s input_offset]\n" - "\t[-o output_file] [-B output_block_size] [-S output_offset]\n", + "\t[-i file] [-b block_size] [-s offset]\n" + "\t[-o file] [-B block_size] [-S offset]\n", program_name); return EX_USAGE; From 67b60e20cc8bb44dc8069a6b2538629f1bbc22ab Mon Sep 17 00:00:00 2001 From: DTB Date: Sat, 29 Jun 2024 05:55:29 -0600 Subject: [PATCH 034/104] dj.1: Man page fixes --- docs/dj.1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 1494827..8fd01f4 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -4,7 +4,7 @@ .\" This work is licensed under CC BY-SA 4.0. To see a copy of this license, .\" visit . .\" -.TH DJ 1 2024-06-17 "Bonsai Core Utilites 0.13.11" +.TH DJ 1 2024-06-29 "Harakit X.X.X" .SH NAME dj \(en disk jockey .\" @@ -73,7 +73,7 @@ null byte is used. Specifies a number of reads to make. The default is 0, in which case the input is read until a partial or empty read is made. .IP \fB-H\fP -Prints diagnostics messages in a human-readable manner as described in the +Prints diagnostic messages in a human-readable manner as described in the DIAGNOSTICS section. .IP \fB-n\fP Retries failed reads once before exiting. @@ -89,7 +89,7 @@ one or more of the input files is \(lq-\(rq. .\" .SH DIAGNOSTICS -On a partial or empty read a diagnostic message is printed. Then, the program +On a partial or empty read, a diagnostic message is printed. Then, the program exits unless the .B -n option is specified. From 6bd19c072d1bf1ab0b8d472c14df66c8b115d6b1 Mon Sep 17 00:00:00 2001 From: DTB Date: Fri, 28 Jun 2024 17:43:32 -0600 Subject: [PATCH 035/104] swab(1): fix some silly mistakes --- src/swab.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/swab.rs b/src/swab.rs index d997ddf..810a6cb 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -24,7 +24,7 @@ use std::{ }; extern crate getopt; -use getopt::{ Opt, Parser }; +use getopt::GetOpt; extern crate sysexits; use sysexits::{ EX_OK, EX_OSERR, EX_USAGE }; @@ -45,7 +45,6 @@ fn main() -> ExitCode { let mut input = stdin(); let mut output = stdout().lock(); - let mut opts = Parser::new(&argv, "fw:"); let mut force = false; let mut wordsize: usize = 2; @@ -53,11 +52,13 @@ fn main() -> ExitCode { match opt.opt() { Ok("f") => force = true, Ok("w") => { - match arg.parse::() { + if let Some(arg) = opt.arg() { + match opt.arg().parse::() { Ok(w) if w % 2 == 0 => { wordsize = w; () }, _ => { return usage(&argv[0]); }, } - }, + } + }, _ => { return usage(&argv[0]); } } } From 17455baeab063443a69d1e73848465ebdc25d254 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 06:38:55 -0600 Subject: [PATCH 036/104] intcmp(1), npc(1): removes vestigial option --- src/intcmp.c | 2 +- src/npc.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/intcmp.c b/src/intcmp.c index 1fd278d..d6dff0d 100644 --- a/src/intcmp.c +++ b/src/intcmp.c @@ -52,7 +52,7 @@ int main(int argc, char *argv[]){ if(optind + 2 /* ref cmp */ > argc){ usage: fprintf(stderr, - "Usage: %s [-eghl] integer integer...\n", + "Usage: %s [-egl] integer integer...\n", argv[0] == NULL ? program_name : argv[0]); return EX_USAGE; } diff --git a/src/npc.c b/src/npc.c index 6b5e5f0..1f96668 100644 --- a/src/npc.c +++ b/src/npc.c @@ -39,7 +39,7 @@ int main(int argc, char *argv[]){ } if(argc > optind){ -usage: fprintf(stderr, "Usage: %s [-eht]\n", argv[0]); +usage: fprintf(stderr, "Usage: %s [-et]\n", argv[0]); return EX_USAGE; } From cf5136d247dcb3329f5f4488d10258449423ae1e Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 07:49:47 -0600 Subject: [PATCH 037/104] Makefile, swab(1): fixes swab build --- Makefile | 6 ++---- src/swab.rs | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 8109cd6..8a9e936 100644 --- a/Makefile +++ b/Makefile @@ -133,10 +133,8 @@ build/bin/strcmp: src/strcmp.c build .PHONY: swab swab: build/bin/swab -build/bin/swab: src/swab.rs build build/o/libsysexits.rlib - $(RUSTC) $(RUSTFLAGS) --extern getopt=build/o/libgetopt.rlib \ - --extern sysexits=build/o/libsysexits.rlib \ - -o $@ src/swab.rs +build/bin/swab: src/swab.rs build rustlibs + $(RUSTC) $(RUSTFLAGS) $(RUSTLIBS) -o $@ src/swab.rs .PHONY: true true: build/bin/true diff --git a/src/swab.rs b/src/swab.rs index 810a6cb..d05b651 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -53,7 +53,7 @@ fn main() -> ExitCode { Ok("f") => force = true, Ok("w") => { if let Some(arg) = opt.arg() { - match opt.arg().parse::() { + match arg.parse::() { Ok(w) if w % 2 == 0 => { wordsize = w; () }, _ => { return usage(&argv[0]); }, } From 40984453e35c452c8ba71b98351a5d692055fc15 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 08:01:33 -0600 Subject: [PATCH 038/104] Makefile: better leverage targets for sysexits build --- Makefile | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 70f53b4..fb9aa5d 100644 --- a/Makefile +++ b/Makefile @@ -76,13 +76,14 @@ build/o/libstrerror.rlib: build src/libstrerror.rs $(RUSTC) $(RUSTFLAGS) --crate-type=lib -o $@ \ src/libstrerror.rs -# bandage solution until bindgen(1) gets stdin support -build/o/libsysexits.rlib: build $(SYSEXITS)sysexits.h - printf '\043define EXIT_FAILURE 1\n' | cat - $(SYSEXITS)sysexits.h \ - > build/include/sysexits.h +build/o/libsysexits.rlib: build/include/sysexits.h bindgen --default-macro-constant-type signed --use-core --formatter=none \ build/include/sysexits.h | $(RUSTC) $(RUSTFLAGS) --crate-type lib -o $@ - +# bandage solution until bindgen(1) gets stdin support +build/include/sysexits.h: build $(SYSEXITS)sysexits.h + printf '\043define EXIT_FAILURE 1\n' | cat - $(SYSEXITS)sysexits.h > $@ + .PHONY: dj dj: build/bin/dj build/bin/dj: src/dj.c build From 261c98ad1446c43e82076950eca0597274f9b211 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 08:24:11 -0600 Subject: [PATCH 039/104] Makefile: docs no longer builds every invocation, normalize PREFIX for setting man dir --- Makefile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index fb9aa5d..99cda9f 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,10 @@ DESTDIR ?= dist PREFIX ?= /usr/local -MANDIR != [ $(PREFIX) = / ] && printf '/usr/share/man\n' \ +# normalized prefix +PREFIX_N != (test -d $(PREFIX) && [ '-' != $(PREFIX) ] \ + && CDPATH= cd -P -- $(PREFIX) && pwd -P) +MANDIR != [ $(PREFIX_N) = / ] && printf '/usr/share/man\n' \ || printf '/share/man\n' SYSEXITS != printf '\043include \n' | cpp -M - | sed 's/ /\n/g' \ | sed -n 's/sysexits\.h//p' || printf 'include\n' @@ -29,7 +32,7 @@ RUSTLIBS = --extern getopt=build/o/libgetopt.rlib \ CFLAGS += -I$(SYSEXITS) .PHONY: all -all: docs dj false fop hru intcmp mm npc rpn scrut str strcmp swab true +all: dj false fop hru intcmp mm npc rpn scrut str strcmp swab true # keep build/include until bindgen(1) has stdin support # https://github.com/rust-lang/rust-bindgen/issues/2703 @@ -40,7 +43,7 @@ build: clean: rm -rf build dist -dist: all +dist: all docs mkdir -p $(DESTDIR)/$(PREFIX)/bin $(DESTDIR)/$(PREFIX)/share/man/man1 cp build/bin/* $(DESTDIR)/$(PREFIX)/bin cp build/docs/*.1 $(DESTDIR)/$(PREFIX)/$(MANDIR)/man1 From e38ea5b35d74e79d427b0cc1c6d01f7a90eb7976 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 29 Jun 2024 08:36:12 -0600 Subject: [PATCH 040/104] Makefile: fixes dist --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 99cda9f..581d2a1 100644 --- a/Makefile +++ b/Makefile @@ -44,7 +44,7 @@ clean: rm -rf build dist dist: all docs - mkdir -p $(DESTDIR)/$(PREFIX)/bin $(DESTDIR)/$(PREFIX)/share/man/man1 + mkdir -p $(DESTDIR)/$(PREFIX)/bin $(DESTDIR)/$(PREFIX)/$(MANDIR)/man1 cp build/bin/* $(DESTDIR)/$(PREFIX)/bin cp build/docs/*.1 $(DESTDIR)/$(PREFIX)/$(MANDIR)/man1 From 6b28a12b731b06abc6691e325d95dbc17523d90a Mon Sep 17 00:00:00 2001 From: DTB Date: Sat, 29 Jun 2024 19:14:08 -0600 Subject: [PATCH 041/104] dj.1: last minute changes --- docs/dj.1 | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 8fd01f4..0e69afc 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -53,9 +53,9 @@ Takes a file path as an argument and opens it for use as an input. Takes a numeric argument as the size in bytes of the input buffer, the default being 1024. .IP \fB-s\fP -Takes a numeric argument as the number of bytes to skip into the input -before starting to read. If the standard input is used, bytes read to this point -are discarded. +Takes a numeric argument as the index of the byte at which reading will +commence; \(lqskips\(rq that number of bytes. If the standard input is used, +bytes read to this point are discarded. .IP \fB-o\fP Takes a file path as an argument and opens it for use as an output. .IP \fB-B\fP @@ -63,8 +63,9 @@ Does the same as .B -b but for the output buffer. .IP \fB-S\fP -Seeks a number of bytes through the output before starting to write from -the input. If the output is a stream, null characters are printed. +Takes a numeric argument as the index of the byte at which writing will +commence; \(lqseeks\(rq that number of bytes. If the standard output is used, +null characters are printed. .IP \fB-a\fP Accepts a single literal byte with which the input buffer is padded in the event of an incomplete read from the input file. If the option argument is empty, the @@ -81,11 +82,11 @@ Retries failed reads once before exiting. .SH STANDARD INPUT The standard input shall be used as an input if no inputs are specified or if -one or more of the input files is \(lq-\(rq. +input file is \(lq-\(rq. .\" .SH STANDARD OUTPUT The standard output shall be used as an output if no inputs are specified or if -one or more of the input files is \(lq-\(rq. +the output file is \(lq-\(rq. .\" .SH DIAGNOSTICS @@ -129,9 +130,7 @@ is specified along with the option and a count, actual byte output is the product of the count and the input block size and therefore may be lower than expected. If the .B -a -or -.B -A -options are specified, this could make written data nonsensical. +option is specified, this could make written data nonsensical. .\" .SH CAVEATS From 984c1c1f9a02033fcf6e6bf3782868aa75118dd2 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 30 Jun 2024 21:21:02 -0600 Subject: [PATCH 042/104] Makefile: fixes portability issue --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 581d2a1..5e2c70d 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ PREFIX_N != (test -d $(PREFIX) && [ '-' != $(PREFIX) ] \ && CDPATH= cd -P -- $(PREFIX) && pwd -P) MANDIR != [ $(PREFIX_N) = / ] && printf '/usr/share/man\n' \ || printf '/share/man\n' -SYSEXITS != printf '\043include \n' | cpp -M - | sed 's/ /\n/g' \ +SYSEXITS != printf '\043include \n' | cpp -M - | tr ' ' '\n' \ | sed -n 's/sysexits\.h//p' || printf 'include\n' CC ?= cc From 064abb82a6f3e4973f3332937c1a9057e7798fd4 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 13:50:24 -0600 Subject: [PATCH 043/104] dj(1): fix option parsing regression --- src/dj.c | 31 ++++--------------------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/src/dj.c b/src/dj.c index d9c38eb..f7e4e9b 100644 --- a/src/dj.c +++ b/src/dj.c @@ -19,7 +19,7 @@ #include /* errno */ #include /* open(2) */ #include /* fprintf(3), stderr */ -#include /* free(3), malloc(3), strtol(3), size_t */ +#include /* malloc(3), strtol(3), size_t */ #include /* memcpy(3), memmove(3), memset(3) */ #include /* EX_OK, EX_USAGE */ #include /* close(2), getopt(3), lseek(2), read(2), write(2), @@ -64,15 +64,6 @@ static int write_flags = O_WRONLY | O_CREAT; || (fd) == STDOUT_FILENO \ || (fd) == STDERR_FILENO) -/* Macro to call the cleanup functions that operate on struct io on the - * particular io[2] used in main. Error conditions are not checked because this - * is only used when the program is about to terminate (hence its name). */ -#define terminate(io) do{ \ - free((io[0]).buf); \ - free((io[1]).buf); \ - Io_fdclose(&(io)[0]); \ - Io_fdclose(&(io)[1]); }while(0) - /* Allocates *io's buffer. Returns NULL if unsuccessful. */ static void * Io_bufalloc(struct Io *io){ @@ -121,15 +112,6 @@ Io_bufxfer(struct Io *dest, struct Io *src, int n){ return dest; } -/* Closes io->fn and returns -1 on error, otherwise io->fd. */ -static int -Io_fdclose(struct Io *io){ - - return fdisstd(io->fd) - ? 0 - : close(io->fd); -} - /* Opens io->fn and saves the file descriptor into io->fd. Returns io->fd, * which will be -1 if an error occured. */ static int @@ -140,7 +122,7 @@ Io_fdopen(struct Io *io, char *fn){ /* these are the flags used by touch(1p) */ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) != -1 - && Io_fdclose(io) == 0){ + && (fdisstd(io->fd) || close(io->fd) == 0)){ io->fd = fd; io->fn = fn; } @@ -294,7 +276,6 @@ int main(int argc, char *argv[]){ break; }else if(Io_fdopen(&io[i], optarg) != -1) break; - terminate(io); return oserr(optarg); case 'n': noerror = 1; break; case 'H': fmt_output = fmt_human; break; @@ -308,19 +289,18 @@ int main(int argc, char *argv[]){ if(c == 'c' && (count = parse(optarg)) >= 0) break; i = (c >= 'A' && c <= 'Z'); /* uppercase changes output */ - c &= 0x20 /* 0b 0010 0000 */; /* (ASCII) make lowercase */ + c |= 0x20 /* 0b 0010 0000 */; /* (ASCII) make lowercase */ if((c == 'b' && (io[i].bs = parse(optarg)) > 0) || (c == 's' && (io[i].seek = parse(optarg)) >= 0)) break; /* FALLTHROUGH */ default: - terminate(io); return usage(program_name); } } + if(argc > optind){ - terminate(io); return usage(program_name); } @@ -328,12 +308,10 @@ int main(int argc, char *argv[]){ if(Io_bufalloc(&io[i]) == NULL){ fprintf(stderr, "%s: Failed to allocate %d bytes\n", program_name, io[i].bs); - terminate(io); return EX_OSERR; }else if(io[i].seek > 0) Io_fdseek(&io[i]); if(io[i].seek > 0){ - terminate(io); return oserr(io[i].fn); } } @@ -387,7 +365,6 @@ int main(int argc, char *argv[]){ }while(count == 0 || --count > 0); output(io, fmt_output); - terminate(io); return EX_OK; } From 1cf67af28179d46b6da387afb691944cc5637d85 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 14:22:23 -0600 Subject: [PATCH 044/104] dj(1): add a ton of assertions, fix if statement, fix io[i] mixups --- src/dj.c | 44 ++++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/src/dj.c b/src/dj.c index f7e4e9b..e5f276b 100644 --- a/src/dj.c +++ b/src/dj.c @@ -16,6 +16,7 @@ * along with this program. If not, see https://www.gnu.org/licenses/. */ +#include /* assert(3) */ #include /* errno */ #include /* open(2) */ #include /* fprintf(3), stderr */ @@ -68,14 +69,18 @@ static int write_flags = O_WRONLY | O_CREAT; static void * Io_bufalloc(struct Io *io){ - return (io->buf = malloc(io->bs * (sizeof *io->buf))); + return io != NULL + ? (io->buf = malloc(io->bs * (sizeof *io->buf))) + : NULL; } /* Fills the unused portion of io's buffer with padding, updating io->bufuse. * Returns io. */ static struct Io * Io_bufrpad(struct Io *io, int padding){ - + + assert(io != NULL); + memset(io->buf + io->bufuse, padding, io->bs - io->bufuse); io->bufuse = io->bs; @@ -90,6 +95,8 @@ static struct Io* Io_bufxapp(struct Io *dest, struct Io *src){ int n; + assert(dest != NULL && src != NULL); + n = MIN(src->bufuse, dest->bs - dest->bufuse); memcpy(dest->buf + dest->bufuse, src->buf, n); dest->bufuse += n; @@ -106,6 +113,8 @@ Io_bufxapp(struct Io *dest, struct Io *src){ static struct Io* Io_bufxfer(struct Io *dest, struct Io *src, int n){ + assert(dest != NULL && src != NULL); + memcpy(dest->buf, src->buf, (dest->bufuse = n)); memmove(src->buf, src->buf + n, (src->bufuse -= n)); @@ -117,7 +126,9 @@ Io_bufxfer(struct Io *dest, struct Io *src, int n){ static int Io_fdopen(struct Io *io, char *fn){ int fd; - + + assert(io != NULL); + if((fd = open(fn, io->fl, /* these are the flags used by touch(1p) */ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) @@ -134,8 +145,15 @@ Io_fdopen(struct Io *io, char *fn){ * of sought bytes from io->seek. This procedure leaves garbage in io->buf. */ static void Io_fdseek(struct Io *io){ - - if(io->seek != 0 + + assert(io != NULL); + assert(io->fd != STDIN_FILENO || io->fl == read_flags); + assert(io->fd != STDOUT_FILENO || io->fl == write_flags); + assert(io->fd != STDERR_FILENO || io->fl == write_flags); + + printf("%s\n", io->fn); + + if(io->seek == 0 || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)) return; @@ -160,7 +178,8 @@ Io_fdseek(struct Io *io){ /* second chance */ io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek)); }while((io->seek -= io->bufuse) > 0 && io->bufuse != 0); - } + }else + assert(0); /* UNREACHABLE */ io->bufuse = 0; @@ -255,9 +274,9 @@ int main(int argc, char *argv[]){ for(i = 0; i < 2; ++i){ io[i].bs = 1024 /* 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ io[i].bytes = 0; - io[i].fd = i ? STDIN_FILENO : STDOUT_FILENO; - io[i].fn = i ? stdin_name : stdout_name; - io[i].fl = i ? read_flags : write_flags; + io[i].fd = i == 0 ? STDIN_FILENO : STDOUT_FILENO; + io[i].fn = i == 0 ? stdin_name : stdout_name; + io[i].fl = i == 0 ? read_flags : write_flags; io[i].prec = 0; io[i].rec = 0; io[i].seek = 0; @@ -271,8 +290,8 @@ int main(int argc, char *argv[]){ switch(c){ case 'i': case 'o': i = (c == 'o'); if(optarg[0] == '-' && optarg[1] == '\0'){ /* optarg == "-" */ - io[i].fd = i ? STDIN_FILENO : STDOUT_FILENO; - io[i].fn = i ? stdin_name : stdout_name; + io[i].fd = i == 0 ? STDIN_FILENO : STDOUT_FILENO; + io[i].fn = i == 0 ? stdin_name : stdout_name; break; }else if(Io_fdopen(&io[i], optarg) != -1) break; @@ -309,11 +328,12 @@ int main(int argc, char *argv[]){ fprintf(stderr, "%s: Failed to allocate %d bytes\n", program_name, io[i].bs); return EX_OSERR; - }else if(io[i].seek > 0) + }else if(io[i].seek > 0){ Io_fdseek(&io[i]); if(io[i].seek > 0){ return oserr(io[i].fn); } + } } do{ /* read */ From 76252305f990c960de08d6793da96a2f0e3a2765 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 14:46:56 -0600 Subject: [PATCH 045/104] dj(1): remove Io_bufalloc --- src/dj.c | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/dj.c b/src/dj.c index e5f276b..2e565ce 100644 --- a/src/dj.c +++ b/src/dj.c @@ -65,15 +65,6 @@ static int write_flags = O_WRONLY | O_CREAT; || (fd) == STDOUT_FILENO \ || (fd) == STDERR_FILENO) -/* Allocates *io's buffer. Returns NULL if unsuccessful. */ -static void * -Io_bufalloc(struct Io *io){ - - return io != NULL - ? (io->buf = malloc(io->bs * (sizeof *io->buf))) - : NULL; -} - /* Fills the unused portion of io's buffer with padding, updating io->bufuse. * Returns io. */ static struct Io * @@ -324,7 +315,7 @@ int main(int argc, char *argv[]){ } for(i = 0; i < 2; ++i){ - if(Io_bufalloc(&io[i]) == NULL){ + if((io[i].buf = malloc(io[i].bs * (sizeof *(io[i].buf)))) == NULL){ fprintf(stderr, "%s: Failed to allocate %d bytes\n", program_name, io[i].bs); return EX_OSERR; From aff658d611e7b221a58b3177f34c7bd5c323d725 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 14:50:50 -0600 Subject: [PATCH 046/104] dj(1): remove debugging vestige, reflow output into printio --- src/dj.c | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/dj.c b/src/dj.c index 2e565ce..a20b472 100644 --- a/src/dj.c +++ b/src/dj.c @@ -47,7 +47,7 @@ struct Io{ long seek; /* bytes to seek/skip (will be 0 after skippage) (-sS) */ }; -/* To be assigned to main:fmt_output and used with output(). */ +/* To be assigned to main:fmt and used with printio(). */ static char *fmt_asv = "%d\037%d\036%d\037%d\035%d\036%d\034"; static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; @@ -142,8 +142,6 @@ Io_fdseek(struct Io *io){ assert(io->fd != STDOUT_FILENO || io->fl == write_flags); assert(io->fd != STDERR_FILENO || io->fl == write_flags); - printf("%s\n", io->fn); - if(io->seek == 0 || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)) return; @@ -215,7 +213,7 @@ oserr(char *s){ /* Prints statistics regarding the use of dj, particularly partially and * completely read and written records. */ static void -output(struct Io io[2], char *fmt){ +printio(char *fmt, struct Io io[2]){ fprintf(stderr, fmt, io[0].rec, io[0].prec, io[1].rec, io[1].prec, @@ -252,7 +250,7 @@ usage(char *s){ int main(int argc, char *argv[]){ int align; /* low 8b used, negative if no alignment is being done */ int count; /* 0 if dj(1) runs until no more reads are possible */ - char *fmt_output; /* == fmt_asv (default) or fmt_human (-H) */ + char *fmt; /* == fmt_asv (default) or fmt_human (-H) */ size_t i; /* side of io being modified */ struct Io io[2]; char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ @@ -260,7 +258,7 @@ int main(int argc, char *argv[]){ /* Set defaults. */ align = -1; count = 0; - fmt_output = fmt_asv; + fmt = fmt_asv; noerror = 0; for(i = 0; i < 2; ++i){ io[i].bs = 1024 /* 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ @@ -288,7 +286,7 @@ int main(int argc, char *argv[]){ break; return oserr(optarg); case 'n': noerror = 1; break; - case 'H': fmt_output = fmt_human; break; + case 'H': fmt = fmt_human; break; case 'a': if(optarg[0] == '\0' || optarg[1] == '\0'){ align = optarg[0]; @@ -298,7 +296,7 @@ int main(int argc, char *argv[]){ case 'c': case 'b': case 's': case 'B': case 'S': /* numbers */ if(c == 'c' && (count = parse(optarg)) >= 0) break; - i = (c >= 'A' && c <= 'Z'); /* uppercase changes output */ + i = (c >= 'A' && c <= 'Z'); c |= 0x20 /* 0b 0010 0000 */; /* (ASCII) make lowercase */ if((c == 'b' && (io[i].bs = parse(optarg)) > 0) || (c == 's' && (io[i].seek = parse(optarg)) >= 0)) @@ -336,7 +334,7 @@ int main(int argc, char *argv[]){ else if(io[0].bufuse < io[0].bs){ ++io[0].prec; fprintf(stderr, "%s: Partial read:\n\t", program_name); - output(io, fmt_output); + printio(fmt, io); if(!noerror) count = 1; if(align >= 0) @@ -365,7 +363,7 @@ int main(int argc, char *argv[]){ }else if(t > io[1].bufuse && io[1].bufuse > 0){ io[1].prec += 1; fprintf(stderr, "%s: Partial write:\n\t", program_name); - output(io, fmt_output); + printio(fmt, io); if(!noerror) count = 1; }else if(io[1].bufuse == 0 && t < io[1].bs) @@ -375,7 +373,7 @@ int main(int argc, char *argv[]){ }while(io[0].bufuse > 0); }while(count == 0 || --count > 0); - output(io, fmt_output); + printio(fmt, io); return EX_OK; } From 6548a448c74d7d226091eff9570dbd34e5f01255 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 15:44:42 -0600 Subject: [PATCH 047/104] dj(1): fix potential skip/seek bug in non-std io --- src/dj.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/dj.c b/src/dj.c index a20b472..41fd65f 100644 --- a/src/dj.c +++ b/src/dj.c @@ -133,7 +133,9 @@ Io_fdopen(struct Io *io, char *fn){ } /* Seeks io->seek bytes through *io's file descriptor, subtracting the number - * of sought bytes from io->seek. This procedure leaves garbage in io->buf. */ + * of sought bytes from io->seek. This procedure leaves garbage in io->buf. + * Read/written bytes here aren't counted in the statistics because successful + * seeking is guaranteed. */ static void Io_fdseek(struct Io *io){ @@ -143,8 +145,10 @@ Io_fdseek(struct Io *io){ assert(io->fd != STDERR_FILENO || io->fl == write_flags); if(io->seek == 0 - || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)) + || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)){ + io->seek = 0; return; + } if(io->fl == write_flags) memset(io->buf, '\0', io->bs); From 3897f44cf8c4379067316415459d2449f014ea70 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 15:46:11 -0600 Subject: [PATCH 048/104] dj(1): prefix getopt optstring with : --- src/dj.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dj.c b/src/dj.c index 41fd65f..f938ca9 100644 --- a/src/dj.c +++ b/src/dj.c @@ -279,7 +279,7 @@ int main(int argc, char *argv[]){ int c; program_name = argv[0]; - while((c = getopt(argc, argv, "a:b:B:c:i:hHns:S:o:")) != -1) + while((c = getopt(argc, argv, ":a:b:B:c:i:hHns:S:o:")) != -1) switch(c){ case 'i': case 'o': i = (c == 'o'); if(optarg[0] == '-' && optarg[1] == '\0'){ /* optarg == "-" */ From 66ca4b9a120a8ce4d6e704d0330f9713194b865c Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 15:47:48 -0600 Subject: [PATCH 049/104] dj(1): remove unnecessary stderr checks --- src/dj.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/dj.c b/src/dj.c index f938ca9..8c9f327 100644 --- a/src/dj.c +++ b/src/dj.c @@ -59,11 +59,8 @@ static int write_flags = O_WRONLY | O_CREAT; #define MIN(a, b) (((a) < (b)) ? (a) : (b)) -/* Macro to check if fd is a std* file, e.g. stdin. */ -#define fdisstd(fd) \ - ((fd) == STDIN_FILENO \ - || (fd) == STDOUT_FILENO \ - || (fd) == STDERR_FILENO) +/* Macro to check if fd is stdin or stdout */ +#define fdisstd(fd) ((fd) == STDIN_FILENO || (fd) == STDOUT_FILENO) /* Fills the unused portion of io's buffer with padding, updating io->bufuse. * Returns io. */ @@ -142,7 +139,6 @@ Io_fdseek(struct Io *io){ assert(io != NULL); assert(io->fd != STDIN_FILENO || io->fl == read_flags); assert(io->fd != STDOUT_FILENO || io->fl == write_flags); - assert(io->fd != STDERR_FILENO || io->fl == write_flags); if(io->seek == 0 || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)){ From 944feef43465caf4ffafc8106373bfbd0d9a090f Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 16:07:02 -0600 Subject: [PATCH 050/104] dj(1): Refactor out Io_fdseek entirely --- src/dj.c | 93 +++++++++++++++++++++++++------------------------------- 1 file changed, 42 insertions(+), 51 deletions(-) diff --git a/src/dj.c b/src/dj.c index 8c9f327..96085e3 100644 --- a/src/dj.c +++ b/src/dj.c @@ -129,52 +129,6 @@ Io_fdopen(struct Io *io, char *fn){ return fd; } -/* Seeks io->seek bytes through *io's file descriptor, subtracting the number - * of sought bytes from io->seek. This procedure leaves garbage in io->buf. - * Read/written bytes here aren't counted in the statistics because successful - * seeking is guaranteed. */ -static void -Io_fdseek(struct Io *io){ - - assert(io != NULL); - assert(io->fd != STDIN_FILENO || io->fl == read_flags); - assert(io->fd != STDOUT_FILENO || io->fl == write_flags); - - if(io->seek == 0 - || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1)){ - io->seek = 0; - return; - } - - if(io->fl == write_flags) - memset(io->buf, '\0', io->bs); - - if(io->fl == write_flags){ - memset(io->buf, '\0', io->bs); - /* We're going to cheat and use bufuse as the retval for write(2), - * which is fine because it'll be zeroed as this function returns - * anyway. */ - do{ - if((io->bufuse = write(io->fd, io->buf, MIN(io->bs, io->seek))) - == 0) - /* second chance */ - io->bufuse = write(io->fd, io->buf, MIN(io->bs, io->seek)); - }while((io->seek -= io->bufuse) > 0 && io->bufuse != 0); - }else if(io->fl == read_flags){ - do{ - if((io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek))) - == 0) - /* second chance */ - io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek)); - }while((io->seek -= io->bufuse) > 0 && io->bufuse != 0); - }else - assert(0); /* UNREACHABLE */ - - io->bufuse = 0; - - return; -} - /* Reads io->bs bytes from *io's file descriptor into io->buf, storing the * number of read bytes in io->bufuse and updating io->bytes. If io->bufuse is * 0, errno will probably be set. Returns io. */ @@ -307,24 +261,61 @@ int main(int argc, char *argv[]){ } } + assert(io->fd != STDIN_FILENO || io->fl == read_flags); + assert(io->fd != STDOUT_FILENO || io->fl == write_flags); if(argc > optind){ return usage(program_name); } for(i = 0; i < 2; ++i){ + /* buffer allocation */ if((io[i].buf = malloc(io[i].bs * (sizeof *(io[i].buf)))) == NULL){ fprintf(stderr, "%s: Failed to allocate %d bytes\n", program_name, io[i].bs); return EX_OSERR; - }else if(io[i].seek > 0){ - Io_fdseek(&io[i]); - if(io[i].seek > 0){ - return oserr(io[i].fn); - } } + /* easy seeking */ + if(!fdisstd(io[i].fd) && lseek(io[i].fd, io[i].seek, SEEK_SET) != -1) + io[i].seek = 0; } + /* hard skipping */ + if(io[0].seek > 0){ + do{ + if((io[0].bufuse = read( + io[0].fd, io[0].buf, MIN(io[0].bs, io[0].seek))) + == 0) + /* second chance */ + io->bufuse = read( + io[0].fd, io[0].buf, MIN(io[0].bs, io[0].seek)); + }while((io[0].seek -= io[0].bufuse) > 0 && io[0].bufuse != 0); + io[0].bufuse = 0; + } + + /* hard seeking */ + if(io[1].seek > 0){ + memset(io[1].buf, '\0', io[1].bs); + /* We're going to cheat and use bufuse as the retval for write(2), + * which is fine because it'll be zeroed as this function returns + * anyway. */ + do{ + if((io[1].bufuse = write( + io[1].fd, io[1].buf, MIN(io[1].bs, io[1].seek))) + == 0) + /* second chance */ + io[1].bufuse = write( + io[1].fd, io[1].buf, MIN(io[1].bs, io[1].seek)); + }while((io[1].seek -= io[1].bufuse) > 0 && io[1].bufuse != 0); + io[1].bufuse = 0; + } + + /* Sought bytes aren't counted in the statistics because successful seeking + * is guaranteed here. */ + for(i = 0; i < 2; ++i) + if(io[i].seek > 0) + return oserr(io[i].fn); + do{ /* read */ Io_read(&io[0]); if(!noerror && io[0].bufuse == 0) From 7fe122ac3b5ee858007c74879f8ee5b4362ec530 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 16:13:20 -0600 Subject: [PATCH 051/104] dj.1: clarify skip/seek behavior with regards to statistics output --- docs/dj.1 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/dj.1 b/docs/dj.1 index 38b8034..dd293f2 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -35,7 +35,9 @@ respectively. This language is inherited from the utility and used here to decrease ambiguity. When seeking or skipping to a byte, writing or reading starts at the byte -immediately subsequent to the specified byte. +immediately subsequent to the specified byte. Seeks and skips aren\(cqt counted +in the output statistics because they're guaranteed to succeed (or the utility +will exit unsuccessfully). .\" .SH OPTIONS From f4b97be1f12d1e212218a4c4e152fb5ca76b7f8c Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 17:50:04 -0600 Subject: [PATCH 052/104] dj(1): iron out Io_bufxapp --- src/dj.c | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/src/dj.c b/src/dj.c index 96085e3..3421292 100644 --- a/src/dj.c +++ b/src/dj.c @@ -75,25 +75,6 @@ Io_bufrpad(struct Io *io, int padding){ return io; } -/* Copies from the buffer in src as much as possible to the free space in the - * dest buffer, removing the copied units from src and permuting the remaining - * units in the src buffer to the start of the buffer, modifying both the src - * and dest bufuse and returning dest. */ -static struct Io* -Io_bufxapp(struct Io *dest, struct Io *src){ - int n; - - assert(dest != NULL && src != NULL); - - n = MIN(src->bufuse, dest->bs - dest->bufuse); - memcpy(dest->buf + dest->bufuse, src->buf, n); - dest->bufuse += n; - memmove(src->buf, src->buf + n, src->bs - n); - src->bufuse -= n; - - return dest; -} - /* Copies from the buffer in src to the buffer in dest no more than n units, * removing the copied units from src and permuting the remaining units in the * src buffer to the start of the buffer, modifying both the src and dest @@ -338,7 +319,16 @@ int main(int argc, char *argv[]){ int t; if(io[1].bs > io[0].bs){ - Io_bufxapp(&io[1], &io[0]); + int n; + + /* copy from ibuf as much as possible to the obuf */ + memcpy(io[1].buf + io[1].bufuse, io[0].buf, + (n = MIN(io[0].bufuse, io[1].bs - io[1].bufuse))); + io[1].bufuse += n; + /* permute out the copied units */ + memmove(io[0].buf, io[0].buf + n, io[0].bs - n); + io[0].bufuse -= n; + if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) continue; /* we could write more */ }else From 2167f35f588c4f87635060b60f8f30192cfe3a47 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 17:59:21 -0600 Subject: [PATCH 053/104] dj(1): fix segfault when bses are mismatched --- src/dj.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/dj.c b/src/dj.c index 3421292..17c1d59 100644 --- a/src/dj.c +++ b/src/dj.c @@ -35,15 +35,15 @@ char *program_name = "dj"; * writing ends of its jockeyed "pipe". User-configurable members are noted * with their relevant options. */ struct Io{ - int bs; /* buffer size (-bB) */ + int bs; /* buffer size (-bB) */ size_t bufuse; /* buffer usage */ char *buf; /* buffer */ - int bytes; /* bytes processed */ + size_t bytes; /* bytes processed */ int fd; /* file descriptor */ int fl; /* file opening flags */ char *fn; /* file name (may be stdin_name or stdout_name) (-io) */ - int prec; /* partial records processed */ - int rec; /* records processed */ + size_t prec; /* partial records processed */ + size_t rec; /* records processed */ long seek; /* bytes to seek/skip (will be 0 after skippage) (-sS) */ }; @@ -197,6 +197,7 @@ int main(int argc, char *argv[]){ noerror = 0; for(i = 0; i < 2; ++i){ io[i].bs = 1024 /* 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ + io[i].bufuse = 0; io[i].bytes = 0; io[i].fd = i == 0 ? STDIN_FILENO : STDOUT_FILENO; io[i].fn = i == 0 ? stdin_name : stdout_name; From adda0d95807085c3685c71accd4bcb4bd4963fc9 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 18:30:54 -0600 Subject: [PATCH 054/104] dj.1: elaborate on skip/seek behavior, provide another example --- docs/dj.1 | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index dd293f2..09f40c9 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -4,7 +4,7 @@ .\" This work is licensed under CC BY-SA 4.0. To see a copy of this license, .\" visit . .\" -.TH DJ 1 2024-06-29 "Harakit X.X.X" +.TH DJ 1 2024-07-03 "Harakit X.X.X" .SH NAME dj \(en disk jockey .\" @@ -34,10 +34,17 @@ respectively. This language is inherited from the .BR dd (1p) utility and used here to decrease ambiguity. -When seeking or skipping to a byte, writing or reading starts at the byte -immediately subsequent to the specified byte. Seeks and skips aren\(cqt counted -in the output statistics because they're guaranteed to succeed (or the utility -will exit unsuccessfully). +The offset used when skipping or seeking refers to how many bytes are skipped +or sought. Running +.BR dj (1) +with a skip offset of 1 skips one byte into the input and reads from the second +byte onwards. A programmer may think of a file as a zero-indexed array of +bytes; in this analogy, the offset given is the index of the byte at which to +start reading or writing. + +Seeks and skips aren\(cqt counted in the output statistics because they're +guaranteed to succeed (or the utility will exit unsuccessfully, before it has +written any data). .\" .SH OPTIONS @@ -82,6 +89,54 @@ input file is \(lq-\(rq. The standard output shall be used as an output if no inputs are specified or if the output file is \(lq-\(rq. .\" +.SH EXAMPLES + +The following +.BR sh (1p) +line: + +.RS +printf 'Hello, world!\(rsn' | dj -c 1 -b 7 -s 7 2>/dev/null +.RE + +Produces the following output: + +.RS +world! +.RE + +The following +.BR sh (1p) +lines run sequentially: + +.RS +tr '\(rs0' 0 Date: Wed, 3 Jul 2024 18:44:42 -0600 Subject: [PATCH 055/104] dj(1): clean up some stray ends --- src/dj.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/dj.c b/src/dj.c index 17c1d59..ac52883 100644 --- a/src/dj.c +++ b/src/dj.c @@ -22,7 +22,7 @@ #include /* fprintf(3), stderr */ #include /* malloc(3), strtol(3), size_t */ #include /* memcpy(3), memmove(3), memset(3) */ -#include /* EX_OK, EX_USAGE */ +#include /* EX_OK, EX_OSERR, EX_USAGE */ #include /* close(2), getopt(3), lseek(2), read(2), write(2), * optarg, optind, STDIN_FILENO, STDOUT_FILENO */ #include /* S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, @@ -246,9 +246,8 @@ int main(int argc, char *argv[]){ assert(io->fd != STDIN_FILENO || io->fl == read_flags); assert(io->fd != STDOUT_FILENO || io->fl == write_flags); - if(argc > optind){ + if(argc > optind) return usage(program_name); - } for(i = 0; i < 2; ++i){ /* buffer allocation */ From b74160fa4e4af5604bb7a3c5278c2b3982094b23 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 19:04:01 -0600 Subject: [PATCH 056/104] dj(1): remove Io_bufxfer --- src/dj.c | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/src/dj.c b/src/dj.c index ac52883..22c46a7 100644 --- a/src/dj.c +++ b/src/dj.c @@ -75,21 +75,6 @@ Io_bufrpad(struct Io *io, int padding){ return io; } -/* Copies from the buffer in src to the buffer in dest no more than n units, - * removing the copied units from src and permuting the remaining units in the - * src buffer to the start of the buffer, modifying both the src and dest - * bufuse and returning dest. */ -static struct Io* -Io_bufxfer(struct Io *dest, struct Io *src, int n){ - - assert(dest != NULL && src != NULL); - - memcpy(dest->buf, src->buf, (dest->bufuse = n)); - memmove(src->buf, src->buf + n, (src->bufuse -= n)); - - return dest; -} - /* Opens io->fn and saves the file descriptor into io->fd. Returns io->fd, * which will be -1 if an error occured. */ static int @@ -318,10 +303,18 @@ int main(int argc, char *argv[]){ do{ int t; - if(io[1].bs > io[0].bs){ + if(io[0].bs <= io[1].bs){ int n; - /* copy from ibuf as much as possible to the obuf */ + /* saturate obuf */ + memcpy(io[1].buf, io[0].buf, + (io[1].bufuse = (n = MIN(io[0].bufuse, io[1].bs)))); + /* permute the copied units out of ibuf */ + memmove(io[0].buf, io[0].buf + n, (io[0].bufuse -= n)); + }else /* if(io[0].bs < io[1].bs) */ { + int n; + + /* drain what we can from ibuf */ memcpy(io[1].buf + io[1].bufuse, io[0].buf, (n = MIN(io[0].bufuse, io[1].bs - io[1].bufuse))); io[1].bufuse += n; @@ -330,9 +323,8 @@ int main(int argc, char *argv[]){ io[0].bufuse -= n; if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) - continue; /* we could write more */ - }else - Io_bufxfer(&io[1], &io[0], MIN(io[0].bufuse, io[1].bs)); + continue; /* obuf not saturated - we could write more */ + } t = io[1].bufuse; Io_write(&io[1]); From 2b593559afc64ad2a7f80bed0511e19250ade41d Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 19:06:59 -0600 Subject: [PATCH 057/104] dj(1): remove Io_bufrpad --- src/dj.c | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/src/dj.c b/src/dj.c index 22c46a7..6815a82 100644 --- a/src/dj.c +++ b/src/dj.c @@ -62,19 +62,6 @@ static int write_flags = O_WRONLY | O_CREAT; /* Macro to check if fd is stdin or stdout */ #define fdisstd(fd) ((fd) == STDIN_FILENO || (fd) == STDOUT_FILENO) -/* Fills the unused portion of io's buffer with padding, updating io->bufuse. - * Returns io. */ -static struct Io * -Io_bufrpad(struct Io *io, int padding){ - - assert(io != NULL); - - memset(io->buf + io->bufuse, padding, io->bs - io->bufuse); - io->bufuse = io->bs; - - return io; -} - /* Opens io->fn and saves the file descriptor into io->fd. Returns io->fd, * which will be -1 if an error occured. */ static int @@ -294,8 +281,12 @@ int main(int argc, char *argv[]){ printio(fmt, io); if(!noerror) count = 1; - if(align >= 0) - Io_bufrpad(&io[0], align); + if(align >= 0){ + /* fill the rest of the ibuf with padding */ + memset(io[0].buf + io[0].bufuse, align, + io[0].bs - io[0].bufuse); + io->bufuse = io->bs; + } }else ++io[0].rec; From 5b1d4fef8828a6057183b95d3828564b4f1811c8 Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 19:22:34 -0600 Subject: [PATCH 058/104] dj(1): remove Io_fdopen --- src/dj.c | 47 +++++++++++++++++++---------------------------- 1 file changed, 19 insertions(+), 28 deletions(-) diff --git a/src/dj.c b/src/dj.c index 6815a82..974bcf0 100644 --- a/src/dj.c +++ b/src/dj.c @@ -62,26 +62,6 @@ static int write_flags = O_WRONLY | O_CREAT; /* Macro to check if fd is stdin or stdout */ #define fdisstd(fd) ((fd) == STDIN_FILENO || (fd) == STDOUT_FILENO) -/* Opens io->fn and saves the file descriptor into io->fd. Returns io->fd, - * which will be -1 if an error occured. */ -static int -Io_fdopen(struct Io *io, char *fn){ - int fd; - - assert(io != NULL); - - if((fd = open(fn, io->fl, - /* these are the flags used by touch(1p) */ - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) - != -1 - && (fdisstd(io->fd) || close(io->fd) == 0)){ - io->fd = fd; - io->fn = fn; - } - - return fd; -} - /* Reads io->bs bytes from *io's file descriptor into io->buf, storing the * number of read bytes in io->bufuse and updating io->bytes. If io->bufuse is * 0, errno will probably be set. Returns io. */ @@ -155,12 +135,12 @@ usage(char *s){ } int main(int argc, char *argv[]){ - int align; /* low 8b used, negative if no alignment is being done */ - int count; /* 0 if dj(1) runs until no more reads are possible */ - char *fmt; /* == fmt_asv (default) or fmt_human (-H) */ - size_t i; /* side of io being modified */ - struct Io io[2]; + int align; /* low 8b used, negative if no alignment is being done */ + int count; /* 0 if dj(1) runs until no more reads are possible */ + char *fmt; /* == fmt_asv (default) or fmt_human (-H) */ + size_t i; /* side of io being modified */ char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ + struct Io io[2]; /* Set defaults. */ align = -1; @@ -190,10 +170,21 @@ int main(int argc, char *argv[]){ io[i].fd = i == 0 ? STDIN_FILENO : STDOUT_FILENO; io[i].fn = i == 0 ? stdin_name : stdout_name; break; - }else if(Io_fdopen(&io[i], optarg) != -1) - break; + }else{ + int fd; + + if((fd = open(optarg, io[i].fl, /* touch(1p) flags */ + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP + | S_IROTH | S_IWOTH)) + != -1 + && (fdisstd(io[i].fd) || close(io[i].fd) == 0)){ + io[i].fd = fd; + io[i].fn = optarg; + break; + } + } return oserr(optarg); - case 'n': noerror = 1; break; + case 'n': noerror = 1; break; case 'H': fmt = fmt_human; break; case 'a': if(optarg[0] == '\0' || optarg[1] == '\0'){ From cc645613888960c2784bcfe5c2a90ce17fe6b2bc Mon Sep 17 00:00:00 2001 From: DTB Date: Wed, 3 Jul 2024 20:52:41 -0600 Subject: [PATCH 059/104] dj(1): only include sysexits if they aren't defined --- src/dj.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/dj.c b/src/dj.c index 974bcf0..5a095ed 100644 --- a/src/dj.c +++ b/src/dj.c @@ -22,7 +22,9 @@ #include /* fprintf(3), stderr */ #include /* malloc(3), strtol(3), size_t */ #include /* memcpy(3), memmove(3), memset(3) */ -#include /* EX_OK, EX_OSERR, EX_USAGE */ +#if !defined EX_OK || !defined EX_OSERR || !defined EX_USAGE +# include +#endif #include /* close(2), getopt(3), lseek(2), read(2), write(2), * optarg, optind, STDIN_FILENO, STDOUT_FILENO */ #include /* S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, From 4004a4a0068f173059ed59c5ac6aba10ec0c6ce6 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 18:41:20 -0600 Subject: [PATCH 060/104] dj(1): use the retvals of Io_read and Io_write --- src/dj.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/dj.c b/src/dj.c index 5a095ed..fa3d46a 100644 --- a/src/dj.c +++ b/src/dj.c @@ -263,8 +263,7 @@ int main(int argc, char *argv[]){ return oserr(io[i].fn); do{ /* read */ - Io_read(&io[0]); - if(!noerror && io[0].bufuse == 0) + if(Io_read(&io[0])->bufuse == 0 && !noerror) Io_read(&io[0]); /* second chance */ if(io[0].bufuse == 0) /* that's all she wrote */ break; @@ -311,8 +310,7 @@ int main(int argc, char *argv[]){ } t = io[1].bufuse; - Io_write(&io[1]); - if(!noerror && io[1].bufuse == t) + if(Io_write(&io[1])->bufuse == t && !noerror) Io_write(&io[1]); /* second chance */ if(t == io[1].bufuse){ /* no more love */ count = 1; From f49a2d2eb8ec3aed83434f164477ff422b3b6b98 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 19:21:40 -0600 Subject: [PATCH 061/104] dj(1): move prec and rec adjustment into Io_read --- src/dj.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/dj.c b/src/dj.c index fa3d46a..9aed880 100644 --- a/src/dj.c +++ b/src/dj.c @@ -65,13 +65,24 @@ static int write_flags = O_WRONLY | O_CREAT; #define fdisstd(fd) ((fd) == STDIN_FILENO || (fd) == STDOUT_FILENO) /* Reads io->bs bytes from *io's file descriptor into io->buf, storing the - * number of read bytes in io->bufuse and updating io->bytes. If io->bufuse is - * 0, errno will probably be set. Returns io. */ + * number of read bytes in io->bufuse and updating io->bytes. If the buf isn't + * saturated but is still read into, io->prec will be incremented. If the buf + * is saturated, io->rec will be incremented. If io->bufuse is 0, errno will + * probably be set. Returns io. */ static struct Io * Io_read(struct Io *io){ io->bytes += (io->bufuse = read(io->fd, io->buf, io->bs)); + assert(io->bufuse <= io->bs); + + if(io->bufuse != 0){ + if(io->bufuse < io->bs) + ++io->prec; + else /* if(io->bufuse == io->bs) */ + ++io->rec; + } + return io; } @@ -267,8 +278,8 @@ int main(int argc, char *argv[]){ Io_read(&io[0]); /* second chance */ if(io[0].bufuse == 0) /* that's all she wrote */ break; - else if(io[0].bufuse < io[0].bs){ - ++io[0].prec; + + if(io[0].bufuse < io[0].bs){ fprintf(stderr, "%s: Partial read:\n\t", program_name); printio(fmt, io); if(!noerror) @@ -279,8 +290,7 @@ int main(int argc, char *argv[]){ io[0].bs - io[0].bufuse); io->bufuse = io->bs; } - }else - ++io[0].rec; + } /* write */ do{ From fc0d9e374bb36198c812bab561b894672ca11fa2 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 19:23:09 -0600 Subject: [PATCH 062/104] dj(1): make printio fprintio --- src/dj.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/dj.c b/src/dj.c index 9aed880..b81deeb 100644 --- a/src/dj.c +++ b/src/dj.c @@ -113,9 +113,9 @@ oserr(char *s){ /* Prints statistics regarding the use of dj, particularly partially and * completely read and written records. */ static void -printio(char *fmt, struct Io io[2]){ +fprintio(FILE *stream, char *fmt, struct Io io[2]){ - fprintf(stderr, fmt, + fprintf(stream, fmt, io[0].rec, io[0].prec, io[1].rec, io[1].prec, io[0].bytes, io[1].bytes); @@ -281,7 +281,7 @@ int main(int argc, char *argv[]){ if(io[0].bufuse < io[0].bs){ fprintf(stderr, "%s: Partial read:\n\t", program_name); - printio(fmt, io); + fprintio(stderr, fmt, io); if(!noerror) count = 1; if(align >= 0){ @@ -328,7 +328,7 @@ int main(int argc, char *argv[]){ }else if(t > io[1].bufuse && io[1].bufuse > 0){ io[1].prec += 1; fprintf(stderr, "%s: Partial write:\n\t", program_name); - printio(fmt, io); + fprintio(stderr, fmt, io); if(!noerror) count = 1; }else if(io[1].bufuse == 0 && t < io[1].bs) @@ -338,7 +338,7 @@ int main(int argc, char *argv[]){ }while(io[0].bufuse > 0); }while(count == 0 || --count > 0); - printio(fmt, io); + fprintio(stderr, fmt, io); return EX_OK; } From f8c0e0570c8896d2e29f0b8bddf2b44c771ba962 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 19:36:32 -0600 Subject: [PATCH 063/104] dj(1): make Io_write handle prec and rec --- src/dj.c | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/dj.c b/src/dj.c index b81deeb..4feae19 100644 --- a/src/dj.c +++ b/src/dj.c @@ -72,30 +72,34 @@ static int write_flags = O_WRONLY | O_CREAT; static struct Io * Io_read(struct Io *io){ + assert(io->bs > 0); + io->bytes += (io->bufuse = read(io->fd, io->buf, io->bs)); assert(io->bufuse <= io->bs); - if(io->bufuse != 0){ - if(io->bufuse < io->bs) - ++io->prec; - else /* if(io->bufuse == io->bs) */ - ++io->rec; - } + io->prec += (0 < io->bufuse && io->bufuse < io->bs); + io->rec += (io->bufuse == io->bs); return io; } -/* Writes io->bufuse units from io->buf to io->fd, permuting any unwritten +/* Writes io->bufuse (>0) units from io->buf to io->fd, permuting any unwritten * bytes to the start of io->buf and updating io->bufuse. If io->bufuse doesn't * change, errno will probably be set. Returns io. */ static struct Io * Io_write(struct Io *io){ int t; + assert(io->bufuse > 0); + assert(io->bufuse <= io->bs); + if((t = write(io->fd, io->buf, io->bufuse)) > 0) memmove(io->buf, io->buf + t, (io->bufuse -= t)); + io->bytes += t; + io->prec += (t > 0 && io->bufuse > 0); + io->rec += (t > 0 && io->bufuse == 0); return io; } @@ -322,19 +326,17 @@ int main(int argc, char *argv[]){ t = io[1].bufuse; if(Io_write(&io[1])->bufuse == t && !noerror) Io_write(&io[1]); /* second chance */ - if(t == io[1].bufuse){ /* no more love */ + if(io[1].bufuse == t){ /* no more love */ count = 1; break; - }else if(t > io[1].bufuse && io[1].bufuse > 0){ - io[1].prec += 1; + } + + if(0 < io[1].bufuse && io[1].bufuse < t){ fprintf(stderr, "%s: Partial write:\n\t", program_name); fprintio(stderr, fmt, io); if(!noerror) count = 1; - }else if(io[1].bufuse == 0 && t < io[1].bs) - ++io[1].prec; - else - ++io[1].rec; + } }while(io[0].bufuse > 0); }while(count == 0 || --count > 0); From 8c33f0116c33834a8ffba6f934cdd99a1cb8453e Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 19:45:53 -0600 Subject: [PATCH 064/104] dj(1): move open(2) flags, remove unnecessary comments --- src/dj.c | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/src/dj.c b/src/dj.c index 4feae19..d5f209c 100644 --- a/src/dj.c +++ b/src/dj.c @@ -56,6 +56,9 @@ static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; static char *stdin_name = ""; static char *stdout_name = ""; + +static int creat_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH + | S_IWOTH; /* Consistent with touch(1p). */ static int read_flags = O_RDONLY; /* Consistent with Busybox dd(1). */ static int write_flags = O_WRONLY | O_CREAT; @@ -64,11 +67,6 @@ static int write_flags = O_WRONLY | O_CREAT; /* Macro to check if fd is stdin or stdout */ #define fdisstd(fd) ((fd) == STDIN_FILENO || (fd) == STDOUT_FILENO) -/* Reads io->bs bytes from *io's file descriptor into io->buf, storing the - * number of read bytes in io->bufuse and updating io->bytes. If the buf isn't - * saturated but is still read into, io->prec will be incremented. If the buf - * is saturated, io->rec will be incremented. If io->bufuse is 0, errno will - * probably be set. Returns io. */ static struct Io * Io_read(struct Io *io){ @@ -84,9 +82,6 @@ Io_read(struct Io *io){ return io; } -/* Writes io->bufuse (>0) units from io->buf to io->fd, permuting any unwritten - * bytes to the start of io->buf and updating io->bufuse. If io->bufuse doesn't - * change, errno will probably be set. Returns io. */ static struct Io * Io_write(struct Io *io){ int t; @@ -190,10 +185,7 @@ int main(int argc, char *argv[]){ }else{ int fd; - if((fd = open(optarg, io[i].fl, /* touch(1p) flags */ - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP - | S_IROTH | S_IWOTH)) - != -1 + if((fd = open(optarg, io[i].fl, creat_mode)) != -1 && (fdisstd(io[i].fd) || close(io[i].fd) == 0)){ io[i].fd = fd; io[i].fn = optarg; From fe175cab191af00bac56042f338ad3f46f5ff617 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 20:00:40 -0600 Subject: [PATCH 065/104] dj(1): add a variable for skipping in the main loop --- src/dj.c | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/src/dj.c b/src/dj.c index d5f209c..9fb55ca 100644 --- a/src/dj.c +++ b/src/dj.c @@ -269,22 +269,29 @@ int main(int argc, char *argv[]){ if(io[i].seek > 0) return oserr(io[i].fn); - do{ /* read */ - if(Io_read(&io[0])->bufuse == 0 && !noerror) - Io_read(&io[0]); /* second chance */ - if(io[0].bufuse == 0) /* that's all she wrote */ - break; + do{ + { /* read */ + static char skipping = 0; - if(io[0].bufuse < io[0].bs){ - fprintf(stderr, "%s: Partial read:\n\t", program_name); - fprintio(stderr, fmt, io); - if(!noerror) - count = 1; - if(align >= 0){ - /* fill the rest of the ibuf with padding */ - memset(io[0].buf + io[0].bufuse, align, - io[0].bs - io[0].bufuse); - io->bufuse = io->bs; + if(io[0].seek > 0) + skipping = 1; + + if(Io_read(&io[0])->bufuse == 0 && !noerror) + Io_read(&io[0]); /* second chance */ + if(io[0].bufuse == 0) /* that's all she wrote */ + break; + + if(io[0].bufuse < io[0].bs){ + fprintf(stderr, "%s: Partial read:\n\t", program_name); + fprintio(stderr, fmt, io); + if(!noerror) + count = 1; + if(align >= 0){ + /* fill the rest of the ibuf with padding */ + memset(io[0].buf + io[0].bufuse, align, + io[0].bs - io[0].bufuse); + io->bufuse = io->bs; + } } } From 1fab60d77939f151627c23f5715fb41633f4ab15 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 20:05:18 -0600 Subject: [PATCH 066/104] dj(1): no more pointer arithmetic --- src/dj.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/dj.c b/src/dj.c index 9fb55ca..e3972aa 100644 --- a/src/dj.c +++ b/src/dj.c @@ -90,7 +90,7 @@ Io_write(struct Io *io){ assert(io->bufuse <= io->bs); if((t = write(io->fd, io->buf, io->bufuse)) > 0) - memmove(io->buf, io->buf + t, (io->bufuse -= t)); + memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); io->bytes += t; io->prec += (t > 0 && io->bufuse > 0); @@ -288,7 +288,7 @@ int main(int argc, char *argv[]){ count = 1; if(align >= 0){ /* fill the rest of the ibuf with padding */ - memset(io[0].buf + io[0].bufuse, align, + memset(&(io[0].buf)[io[0].bufuse], align, io[0].bs - io[0].bufuse); io->bufuse = io->bs; } @@ -306,16 +306,16 @@ int main(int argc, char *argv[]){ memcpy(io[1].buf, io[0].buf, (io[1].bufuse = (n = MIN(io[0].bufuse, io[1].bs)))); /* permute the copied units out of ibuf */ - memmove(io[0].buf, io[0].buf + n, (io[0].bufuse -= n)); + memmove(io[0].buf, &(io[0].buf)[n], (io[0].bufuse -= n)); }else /* if(io[0].bs < io[1].bs) */ { int n; /* drain what we can from ibuf */ - memcpy(io[1].buf + io[1].bufuse, io[0].buf, + memcpy(&(io[1].buf)[io[1].bufuse], io[0].buf, (n = MIN(io[0].bufuse, io[1].bs - io[1].bufuse))); io[1].bufuse += n; /* permute out the copied units */ - memmove(io[0].buf, io[0].buf + n, io[0].bs - n); + memmove(io[0].buf, &{io[0].buf)[n], io[0].bs - n); io[0].bufuse -= n; if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) From 9f420131ee591ad97847cc1599c05fbd8b2e0203 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 20:16:54 -0600 Subject: [PATCH 067/104] dj(1): more work adapting hard skipping to the main loop --- src/dj.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/dj.c b/src/dj.c index e3972aa..aee9c38 100644 --- a/src/dj.c +++ b/src/dj.c @@ -270,23 +270,27 @@ int main(int argc, char *argv[]){ return oserr(io[i].fn); do{ + assert(io[0].bufuse == 0); + { /* read */ static char skipping = 0; + int t; if(io[0].seek > 0) skipping = 1; - if(Io_read(&io[0])->bufuse == 0 && !noerror) + t = io[0].bufuse; + if(Io_read(&io[0])->bufuse == t && !noerror) Io_read(&io[0]); /* second chance */ - if(io[0].bufuse == 0) /* that's all she wrote */ + if(io[0].bufuse == t) /* that's all she wrote */ break; - if(io[0].bufuse < io[0].bs){ + if(/* t < io[0].bufuse && */ io[0].bufuse < io[0].bs){ fprintf(stderr, "%s: Partial read:\n\t", program_name); fprintio(stderr, fmt, io); if(!noerror) count = 1; - if(align >= 0){ + if(!skipping && align >= 0){ /* fill the rest of the ibuf with padding */ memset(&(io[0].buf)[io[0].bufuse], align, io[0].bs - io[0].bufuse); @@ -315,7 +319,7 @@ int main(int argc, char *argv[]){ (n = MIN(io[0].bufuse, io[1].bs - io[1].bufuse))); io[1].bufuse += n; /* permute out the copied units */ - memmove(io[0].buf, &{io[0].buf)[n], io[0].bs - n); + memmove(io[0].buf, &(io[0].buf)[n], io[0].bs - n); io[0].bufuse -= n; if(io[0].bs + io[1].bufuse <= io[1].bs && count != 1) @@ -330,7 +334,7 @@ int main(int argc, char *argv[]){ break; } - if(0 < io[1].bufuse && io[1].bufuse < t){ + if(0 < io[1].bufuse /* && io[1].bufuse < t */){ fprintf(stderr, "%s: Partial write:\n\t", program_name); fprintio(stderr, fmt, io); if(!noerror) From 906eb92f5a59995a5b5a977ee2667b9a47b3ddec Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 20:27:31 -0600 Subject: [PATCH 068/104] dj(1): (broken) move hard skipping to the main loop --- src/dj.c | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/src/dj.c b/src/dj.c index aee9c38..7b3bb0a 100644 --- a/src/dj.c +++ b/src/dj.c @@ -72,7 +72,8 @@ Io_read(struct Io *io){ assert(io->bs > 0); - io->bytes += (io->bufuse = read(io->fd, io->buf, io->bs)); + io->bytes += (io->bufuse = read(io->fd, &(io->buf)[io->bufuse], + io->bs - io->bufuse)); assert(io->bufuse <= io->bs); @@ -233,19 +234,6 @@ int main(int argc, char *argv[]){ io[i].seek = 0; } - /* hard skipping */ - if(io[0].seek > 0){ - do{ - if((io[0].bufuse = read( - io[0].fd, io[0].buf, MIN(io[0].bs, io[0].seek))) - == 0) - /* second chance */ - io->bufuse = read( - io[0].fd, io[0].buf, MIN(io[0].bs, io[0].seek)); - }while((io[0].seek -= io[0].bufuse) > 0 && io[0].bufuse != 0); - io[0].bufuse = 0; - } - /* hard seeking */ if(io[1].seek > 0){ memset(io[1].buf, '\0', io[1].bs); @@ -265,9 +253,8 @@ int main(int argc, char *argv[]){ /* Sought bytes aren't counted in the statistics because successful seeking * is guaranteed here. */ - for(i = 0; i < 2; ++i) - if(io[i].seek > 0) - return oserr(io[i].fn); + if(io[1].seek > 0) + return oserr(io[1].fn); do{ assert(io[0].bufuse == 0); @@ -279,6 +266,9 @@ int main(int argc, char *argv[]){ if(io[0].seek > 0) skipping = 1; + if(skipping && io[0].seek < io[0].bs) + io[0].bufuse = io[0].bs - io[0].seek; + t = io[0].bufuse; if(Io_read(&io[0])->bufuse == t && !noerror) Io_read(&io[0]); /* second chance */ @@ -297,6 +287,13 @@ int main(int argc, char *argv[]){ io->bufuse = io->bs; } } + + if(skipping){ + skipping = (io[0].seek -= io[0].bufuse - t) > 0; + io[0].bufuse = 0; + count += (count != 0); + continue; + } } /* write */ From 9e8b82c4bbf402c5caec14c0dd4a74acf8ccf35e Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 20:47:30 -0600 Subject: [PATCH 069/104] dj(1): fix inaccurate statistics after Io_read and Io_write --- src/dj.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/dj.c b/src/dj.c index 7b3bb0a..e65274a 100644 --- a/src/dj.c +++ b/src/dj.c @@ -69,16 +69,19 @@ static int write_flags = O_WRONLY | O_CREAT; static struct Io * Io_read(struct Io *io){ + int t; assert(io->bs > 0); + assert(io->bufuse < io->bs); - io->bytes += (io->bufuse = read(io->fd, &(io->buf)[io->bufuse], + io->bufuse += (t = read(io->fd, &(io->buf)[io->bufuse], io->bs - io->bufuse)); assert(io->bufuse <= io->bs); - io->prec += (0 < io->bufuse && io->bufuse < io->bs); - io->rec += (io->bufuse == io->bs); + io->bytes += t; + io->prec += (0 < io->bufuse && io->bufuse < io->bs); + io->rec += (io->bufuse == io->bs); return io; } @@ -94,8 +97,8 @@ Io_write(struct Io *io){ memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); io->bytes += t; - io->prec += (t > 0 && io->bufuse > 0); - io->rec += (t > 0 && io->bufuse == 0); + io->prec += (0 < io->bufuse && 0 < t); + io->rec += (io->bufuse == 0 && 0 < t); return io; } From 571796fe0d6ae440ff849f6a6ccbbba5e7760dd0 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 21:05:15 -0600 Subject: [PATCH 070/104] dj.1: update man page to match behavior --- docs/dj.1 | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 09f40c9..4c60ff7 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -42,9 +42,9 @@ byte onwards. A programmer may think of a file as a zero-indexed array of bytes; in this analogy, the offset given is the index of the byte at which to start reading or writing. -Seeks and skips aren\(cqt counted in the output statistics because they're -guaranteed to succeed (or the utility will exit unsuccessfully, before it has -written any data). +Seeks aren\(cqt counted in the output statistics because they\(cqre guaranteed +to succeed (or the utility will exit unsuccessfully, before it has written any +data). .\" .SH OPTIONS @@ -185,9 +185,19 @@ option is specified, this could make written data nonsensical. Existing files are not truncated on ouput and are instead overwritten. -Many lowercase options have capitalized variants and vice-versa which can be -confusing. Capitalized options tend to affect output or are more intense -versions of lowercase options. +The options +.B -b +and +.B -B +could be confused for each other, and so could +.B -s +and +.BR -S . +The lowercase option affects input and the capitalized option affects output. + +The discarded but read bytes skipped while processing irregular files, such as +streams, are reported in the diagnostic output. Bytes skipped while processing +regular files are not reported, as the bytes weren\(cqt read. .\" .SH RATIONALE @@ -208,3 +218,4 @@ Copyright \(co 2023 DTB. License AGPLv3+: GNU AGPL version 3 or later .\" .SH SEE ALSO .BR dd (1p) +.BR lseek (3p) From 6ed7089b25852f41f882f4a42829e22f107259d3 Mon Sep 17 00:00:00 2001 From: DTB Date: Thu, 4 Jul 2024 21:32:05 -0600 Subject: [PATCH 071/104] dj(1): statistics now track hard seeks --- docs/dj.1 | 11 ++++------- src/dj.c | 36 ++++++++++++++---------------------- 2 files changed, 18 insertions(+), 29 deletions(-) diff --git a/docs/dj.1 b/docs/dj.1 index 4c60ff7..d358e3f 100644 --- a/docs/dj.1 +++ b/docs/dj.1 @@ -41,10 +41,6 @@ with a skip offset of 1 skips one byte into the input and reads from the second byte onwards. A programmer may think of a file as a zero-indexed array of bytes; in this analogy, the offset given is the index of the byte at which to start reading or writing. - -Seeks aren\(cqt counted in the output statistics because they\(cqre guaranteed -to succeed (or the utility will exit unsuccessfully, before it has written any -data). .\" .SH OPTIONS @@ -195,9 +191,10 @@ and .BR -S . The lowercase option affects input and the capitalized option affects output. -The discarded but read bytes skipped while processing irregular files, such as -streams, are reported in the diagnostic output. Bytes skipped while processing -regular files are not reported, as the bytes weren\(cqt read. +The skipped or sought bytes while processing irregular files, such as streams, +are reported in the diagnostic output, because they were actually read or +written. This is as opposed to bytes skipped while processing regular files, +which are not reported. .\" .SH RATIONALE diff --git a/src/dj.c b/src/dj.c index e65274a..08df495 100644 --- a/src/dj.c +++ b/src/dj.c @@ -56,7 +56,6 @@ static char *fmt_human = "%d+%d > %d+%d; %d > %d\n"; static char *stdin_name = ""; static char *stdout_name = ""; - static int creat_mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; /* Consistent with touch(1p). */ static int read_flags = O_RDONLY; /* Consistent with Busybox dd(1). */ @@ -239,37 +238,29 @@ int main(int argc, char *argv[]){ /* hard seeking */ if(io[1].seek > 0){ - memset(io[1].buf, '\0', io[1].bs); - /* We're going to cheat and use bufuse as the retval for write(2), - * which is fine because it'll be zeroed as this function returns - * anyway. */ + size_t t; do{ - if((io[1].bufuse = write( - io[1].fd, io[1].buf, MIN(io[1].bs, io[1].seek))) - == 0) - /* second chance */ - io[1].bufuse = write( - io[1].fd, io[1].buf, MIN(io[1].bs, io[1].seek)); - }while((io[1].seek -= io[1].bufuse) > 0 && io[1].bufuse != 0); + memset(io[1].buf, '\0', + (t = io[1].bufuse = MIN(io[1].bs, io[1].seek))); + if(Io_write(&io[1])->bufuse == t && !noerror) + Io_write(&io[1]); /* second chance */ + }while((io[1].seek -= (t - io[1].bufuse)) > 0 && io[1].bufuse != t); io[1].bufuse = 0; } - /* Sought bytes aren't counted in the statistics because successful seeking - * is guaranteed here. */ - if(io[1].seek > 0) + if(io[1].seek > 0){ + fprintio(stderr, fmt, io); return oserr(io[1].fn); + } do{ assert(io[0].bufuse == 0); { /* read */ - static char skipping = 0; + char skipping; int t; - if(io[0].seek > 0) - skipping = 1; - - if(skipping && io[0].seek < io[0].bs) + if((skipping = (io[0].seek > 0)) && io[0].seek < io[0].bs) io[0].bufuse = io[0].bs - io[0].seek; t = io[0].bufuse; @@ -279,11 +270,13 @@ int main(int argc, char *argv[]){ break; if(/* t < io[0].bufuse && */ io[0].bufuse < io[0].bs){ + assert(!skipping); + fprintf(stderr, "%s: Partial read:\n\t", program_name); fprintio(stderr, fmt, io); if(!noerror) count = 1; - if(!skipping && align >= 0){ + if(align >= 0){ /* fill the rest of the ibuf with padding */ memset(&(io[0].buf)[io[0].bufuse], align, io[0].bs - io[0].bufuse); @@ -292,7 +285,6 @@ int main(int argc, char *argv[]){ } if(skipping){ - skipping = (io[0].seek -= io[0].bufuse - t) > 0; io[0].bufuse = 0; count += (count != 0); continue; From abfe7046e77a3103f01f9b1f7ae9dddf082062ef Mon Sep 17 00:00:00 2001 From: DTB Date: Fri, 5 Jul 2024 08:02:09 -0600 Subject: [PATCH 072/104] dj(1): fix some type issues --- src/dj.c | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/dj.c b/src/dj.c index 08df495..2be2ecb 100644 --- a/src/dj.c +++ b/src/dj.c @@ -73,15 +73,16 @@ Io_read(struct Io *io){ assert(io->bs > 0); assert(io->bufuse < io->bs); - io->bufuse += (t = read(io->fd, &(io->buf)[io->bufuse], - io->bs - io->bufuse)); + if((t = read(io->fd, &(io->buf)[io->bufuse], io->bs - io->bufuse)) < 0) + t = 0; + + io->bufuse += t; + io->bytes += t; + io->prec += (0 < io->bufuse && io->bufuse < io->bs); + io->rec += (io->bufuse == io->bs); assert(io->bufuse <= io->bs); - io->bytes += t; - io->prec += (0 < io->bufuse && io->bufuse < io->bs); - io->rec += (io->bufuse == io->bs); - return io; } @@ -96,8 +97,8 @@ Io_write(struct Io *io){ memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); io->bytes += t; - io->prec += (0 < io->bufuse && 0 < t); - io->rec += (io->bufuse == 0 && 0 < t); + io->prec += (t > 0 && io->bufuse > 0); + io->rec += (t > 0 && io->bufuse == 0); return io; } @@ -258,8 +259,9 @@ int main(int argc, char *argv[]){ { /* read */ char skipping; - int t; + size_t t; + /* hack to intentionally get a partial read from Io_read */ if((skipping = (io[0].seek > 0)) && io[0].seek < io[0].bs) io[0].bufuse = io[0].bs - io[0].seek; @@ -270,8 +272,6 @@ int main(int argc, char *argv[]){ break; if(/* t < io[0].bufuse && */ io[0].bufuse < io[0].bs){ - assert(!skipping); - fprintf(stderr, "%s: Partial read:\n\t", program_name); fprintio(stderr, fmt, io); if(!noerror) From bab3cdd90e8ef97a4aa71593edf67c4bb8fa4c09 Mon Sep 17 00:00:00 2001 From: DTB Date: Sun, 7 Jul 2024 18:14:48 -0600 Subject: [PATCH 073/104] dj(1): Io_write: don't add to bufuse --- src/dj.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/dj.c b/src/dj.c index 2be2ecb..4dc4842 100644 --- a/src/dj.c +++ b/src/dj.c @@ -93,7 +93,9 @@ Io_write(struct Io *io){ assert(io->bufuse > 0); assert(io->bufuse <= io->bs); - if((t = write(io->fd, io->buf, io->bufuse)) > 0) + if((t = write(io->fd, io->buf, io->bufuse)) < 0) + t = 0; + else if(t > 0) memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); io->bytes += t; @@ -268,6 +270,7 @@ int main(int argc, char *argv[]){ t = io[0].bufuse; if(Io_read(&io[0])->bufuse == t && !noerror) Io_read(&io[0]); /* second chance */ + assert(io[0].bufuse >= t); if(io[0].bufuse == t) /* that's all she wrote */ break; @@ -321,6 +324,7 @@ int main(int argc, char *argv[]){ t = io[1].bufuse; if(Io_write(&io[1])->bufuse == t && !noerror) Io_write(&io[1]); /* second chance */ + assert(io[1].bufuse <= t); if(io[1].bufuse == t){ /* no more love */ count = 1; break; From cf744efc1b13d7482c2f234c9f05490e443bb8f3 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 7 Jul 2024 18:21:48 -0600 Subject: [PATCH 074/104] swab(1): fixes not using strerror(3) --- src/swab.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/swab.rs b/src/swab.rs index e723819..5942c38 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -29,8 +29,11 @@ use getopt::GetOpt; extern crate sysexits; use sysexits::{ EX_OK, EX_OSERR, EX_USAGE }; +extern crate strerror; +use strerror::StrError; + fn oserr(s: &str, e: Error) -> ExitCode { - eprintln!("{}: {}", s, e); + eprintln!("{}: {}", s, e.strerror()); ExitCode::from(EX_OSERR as u8) } From 691e94c0c1542a3cdbe6f683e42e8854b5485bbc Mon Sep 17 00:00:00 2001 From: DTB Date: Sun, 7 Jul 2024 20:33:54 -0600 Subject: [PATCH 075/104] dj(1): error reporting more of the time --- src/dj.c | 49 +++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/src/dj.c b/src/dj.c index 4dc4842..88c3979 100644 --- a/src/dj.c +++ b/src/dj.c @@ -37,17 +37,18 @@ char *program_name = "dj"; * writing ends of its jockeyed "pipe". User-configurable members are noted * with their relevant options. */ struct Io{ - int bs; /* buffer size (-bB) */ + char *buf; /* buffer */ + char *fn; /* file name (-io) */ + size_t bs; /* buffer size (-bB) */ size_t bufuse; /* buffer usage */ - char *buf; /* buffer */ - size_t bytes; /* bytes processed */ - int fd; /* file descriptor */ - int fl; /* file opening flags */ - char *fn; /* file name (may be stdin_name or stdout_name) (-io) */ - size_t prec; /* partial records processed */ - size_t rec; /* records processed */ - long seek; /* bytes to seek/skip (will be 0 after skippage) (-sS) */ -}; + size_t bytes; /* bytes processed */ + size_t prec; /* partial records processed */ + size_t rec; /* records processed */ + long seek; /* remaining bytes to seek/skip (-sS) */ + int fd; /* file descriptor */ + int fl; /* file opening flags */ + char error: 1; /* (bool) error status */ +}; /* To be assigned to main:fmt and used with printio(). */ static char *fmt_asv = "%d\037%d\036%d\037%d\035%d\036%d\034"; @@ -73,8 +74,10 @@ Io_read(struct Io *io){ assert(io->bs > 0); assert(io->bufuse < io->bs); - if((t = read(io->fd, &(io->buf)[io->bufuse], io->bs - io->bufuse)) < 0) + if((t = read(io->fd, &(io->buf)[io->bufuse], io->bs - io->bufuse)) < 0){ + io->error = 1; t = 0; + } io->bufuse += t; io->bytes += t; @@ -93,9 +96,10 @@ Io_write(struct Io *io){ assert(io->bufuse > 0); assert(io->bufuse <= io->bs); - if((t = write(io->fd, io->buf, io->bufuse)) < 0) + if((t = write(io->fd, io->buf, io->bufuse)) < 0){ + io->error = 1; t = 0; - else if(t > 0) + }else if(t > 0) memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); io->bytes += t; @@ -158,20 +162,21 @@ int main(int argc, char *argv[]){ char *fmt; /* == fmt_asv (default) or fmt_human (-H) */ size_t i; /* side of io being modified */ char noerror; /* 0=exits (default) 1=retries on partial reads or writes */ - struct Io io[2]; + struct Io io[2 /* { in, out } */]; /* Set defaults. */ align = -1; count = 0; fmt = fmt_asv; noerror = 0; - for(i = 0; i < 2; ++i){ + for(i = 0; i < (sizeof io) / (sizeof *io); ++i){ io[i].bs = 1024 /* 1 KiB */; /* GNU dd(1) default; POSIX says 512B */ io[i].bufuse = 0; io[i].bytes = 0; io[i].fd = i == 0 ? STDIN_FILENO : STDOUT_FILENO; io[i].fn = i == 0 ? stdin_name : stdout_name; io[i].fl = i == 0 ? read_flags : write_flags; + io[i].error = 0; io[i].prec = 0; io[i].rec = 0; io[i].seek = 0; @@ -227,10 +232,10 @@ int main(int argc, char *argv[]){ if(argc > optind) return usage(program_name); - for(i = 0; i < 2; ++i){ + for(i = 0; i < (sizeof io) / (sizeof *io); ++i){ /* buffer allocation */ if((io[i].buf = malloc(io[i].bs * (sizeof *(io[i].buf)))) == NULL){ - fprintf(stderr, "%s: Failed to allocate %d bytes\n", + fprintf(stderr, "%s: Failed to allocate %zd bytes\n", program_name, io[i].bs); return EX_OSERR; } @@ -245,7 +250,7 @@ int main(int argc, char *argv[]){ do{ memset(io[1].buf, '\0', (t = io[1].bufuse = MIN(io[1].bs, io[1].seek))); - if(Io_write(&io[1])->bufuse == t && !noerror) + if(Io_write(&io[1])->bufuse == t && !noerror && !io[1].error) Io_write(&io[1]); /* second chance */ }while((io[1].seek -= (t - io[1].bufuse)) > 0 && io[1].bufuse != t); io[1].bufuse = 0; @@ -268,7 +273,7 @@ int main(int argc, char *argv[]){ io[0].bufuse = io[0].bs - io[0].seek; t = io[0].bufuse; - if(Io_read(&io[0])->bufuse == t && !noerror) + if(Io_read(&io[0])->bufuse == t && !noerror && io[0].error) Io_read(&io[0]); /* second chance */ assert(io[0].bufuse >= t); if(io[0].bufuse == t) /* that's all she wrote */ @@ -322,7 +327,7 @@ int main(int argc, char *argv[]){ } t = io[1].bufuse; - if(Io_write(&io[1])->bufuse == t && !noerror) + if(Io_write(&io[1])->bufuse == t && !noerror && !io[1].error) Io_write(&io[1]); /* second chance */ assert(io[1].bufuse <= t); if(io[1].bufuse == t){ /* no more love */ @@ -341,5 +346,9 @@ int main(int argc, char *argv[]){ fprintio(stderr, fmt, io); + for(i = 0; i < (sizeof io) / (sizeof *io); ++i) + if(io[i].error) + return oserr(io[i].fn); + return EX_OK; } From 5d5a6d2172a5e33399fe143265a205b5f7ffdffb Mon Sep 17 00:00:00 2001 From: DTB Date: Sun, 7 Jul 2024 21:13:44 -0600 Subject: [PATCH 076/104] dj(1): fix retvals --- src/dj.c | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/dj.c b/src/dj.c index 88c3979..8fe1af3 100644 --- a/src/dj.c +++ b/src/dj.c @@ -45,9 +45,9 @@ struct Io{ size_t prec; /* partial records processed */ size_t rec; /* records processed */ long seek; /* remaining bytes to seek/skip (-sS) */ + int error; /* errno */ int fd; /* file descriptor */ int fl; /* file opening flags */ - char error: 1; /* (bool) error status */ }; /* To be assigned to main:fmt and used with printio(). */ @@ -75,7 +75,7 @@ Io_read(struct Io *io){ assert(io->bufuse < io->bs); if((t = read(io->fd, &(io->buf)[io->bufuse], io->bs - io->bufuse)) < 0){ - io->error = 1; + io->error = errno; t = 0; } @@ -97,7 +97,7 @@ Io_write(struct Io *io){ assert(io->bufuse <= io->bs); if((t = write(io->fd, io->buf, io->bufuse)) < 0){ - io->error = 1; + io->error = errno; t = 0; }else if(t > 0) memmove(io->buf, &(io->buf)[t], (io->bufuse -= t)); @@ -109,13 +109,9 @@ Io_write(struct Io *io){ return io; } -/* Prints an error message suitable for the event of an operating system error, - * with the error itself to be described in the string s. */ static int -oserr(char *s){ - - fprintf(stderr, "%s: %s: %s\n", program_name, s, strerror(errno)); - +oserr(char *e, int n){ + fprintf(stderr, "%s: %s: %s\n", program_name, e, strerror(n)); return EX_OSERR; } @@ -203,7 +199,7 @@ int main(int argc, char *argv[]){ break; } } - return oserr(optarg); + return oserr(optarg, errno); case 'n': noerror = 1; break; case 'H': fmt = fmt_human; break; case 'a': @@ -250,15 +246,17 @@ int main(int argc, char *argv[]){ do{ memset(io[1].buf, '\0', (t = io[1].bufuse = MIN(io[1].bs, io[1].seek))); - if(Io_write(&io[1])->bufuse == t && !noerror && !io[1].error) + if(Io_write(&io[1])->bufuse == t && !noerror && io[1].error == 0) Io_write(&io[1]); /* second chance */ + if(io[1].error != 0) + return oserr(io[1].fn, io[1].error); }while((io[1].seek -= (t - io[1].bufuse)) > 0 && io[1].bufuse != t); io[1].bufuse = 0; } if(io[1].seek > 0){ fprintio(stderr, fmt, io); - return oserr(io[1].fn); + return oserr(io[1].fn, errno); } do{ @@ -273,7 +271,7 @@ int main(int argc, char *argv[]){ io[0].bufuse = io[0].bs - io[0].seek; t = io[0].bufuse; - if(Io_read(&io[0])->bufuse == t && !noerror && io[0].error) + if(Io_read(&io[0])->bufuse == t && !noerror && io[0].error == 0) Io_read(&io[0]); /* second chance */ assert(io[0].bufuse >= t); if(io[0].bufuse == t) /* that's all she wrote */ @@ -327,7 +325,7 @@ int main(int argc, char *argv[]){ } t = io[1].bufuse; - if(Io_write(&io[1])->bufuse == t && !noerror && !io[1].error) + if(Io_write(&io[1])->bufuse == t && !noerror && io[1].error == 0) Io_write(&io[1]); /* second chance */ assert(io[1].bufuse <= t); if(io[1].bufuse == t){ /* no more love */ @@ -348,7 +346,7 @@ int main(int argc, char *argv[]){ for(i = 0; i < (sizeof io) / (sizeof *io); ++i) if(io[i].error) - return oserr(io[i].fn); + return oserr(io[i].fn, io[i].error); return EX_OK; } From a141b952935a8ba07768dd17473564e9604ae0d3 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 11:30:21 -0600 Subject: [PATCH 077/104] swab(1): remove -f --- docs/swab.1 | 3 --- src/swab.rs | 9 +++------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/docs/swab.1 b/docs/swab.1 index 42eef95..7c50b15 100644 --- a/docs/swab.1 +++ b/docs/swab.1 @@ -11,7 +11,6 @@ swab \(en swap bytes .SH SYNOPSIS swab -.RB [ -f ] .RB [ -w\ word_size ] .\" .SH DESCRIPTION @@ -20,8 +19,6 @@ Swap the latter and former halves of a block of bytes. .\" .SH OPTIONS -.IP \fB-f\fP -Ignore SIGINT signal. .IP \fB-w\fP\ \fIword_size\fP Configures the word size; that is, the size in bytes of the block size on which to operate. The default word size is 2. The word size must be cleanly divisible diff --git a/src/swab.rs b/src/swab.rs index 5942c38..3bb40a5 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -18,7 +18,7 @@ use std::{ env::args, - io::{ stdin, stdout, Error, ErrorKind, Read, Write }, + io::{ stdin, stdout, Error, Read, Write }, process::ExitCode, vec::Vec }; @@ -38,7 +38,7 @@ fn oserr(s: &str, e: Error) -> ExitCode { } fn usage(s: &str) -> ExitCode { - eprintln!("Usage: {} [-f] [-w word_size]", s); + eprintln!("Usage: {} [-w word_size]", s); ExitCode::from(EX_USAGE as u8) } @@ -48,12 +48,10 @@ fn main() -> ExitCode { let mut input = stdin(); let mut output = stdout().lock(); - let mut force = false; let mut wordsize: usize = 2; - while let Some(opt) = argv.getopt("fw:") { + while let Some(opt) = argv.getopt("w:") { match opt.opt() { - Ok("f") => force = true, Ok("w") => { if let Some(arg) = opt.arg() { match arg.parse::() { @@ -83,7 +81,6 @@ fn main() -> ExitCode { break oserr(&argv[0], e) } }, - Err(e) if e.kind() == ErrorKind::Interrupted && force => continue, Err(e) => break oserr(&argv[0], e) } } From 35d54d84b0cc7675e72927b9c9513d4344c4f2cd Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 11:31:35 -0600 Subject: [PATCH 078/104] swab(1): don't use the getopt error message --- src/swab.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/swab.rs b/src/swab.rs index 3bb40a5..7889a59 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -50,7 +50,7 @@ fn main() -> ExitCode { let mut wordsize: usize = 2; - while let Some(opt) = argv.getopt("w:") { + while let Some(opt) = argv.getopt(":w:") { match opt.opt() { Ok("w") => { if let Some(arg) = opt.arg() { From 1fd768057cd0c4fc6ed47e1a9b77ffed2fe608e9 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 11:45:01 -0600 Subject: [PATCH 079/104] swab(1): don't accept positional arguments --- src/swab.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/swab.rs b/src/swab.rs index 7889a59..5b4c173 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -48,7 +48,8 @@ fn main() -> ExitCode { let mut input = stdin(); let mut output = stdout().lock(); - let mut wordsize: usize = 2; + let mut optind: usize = 1; // argv[0] + let mut wordsize: usize = 2; // Equivalent to dd(1p). while let Some(opt) = argv.getopt(":w:") { match opt.opt() { @@ -59,11 +60,16 @@ fn main() -> ExitCode { _ => { return usage(&argv[0]); }, } } + optind = opt.ind(); }, _ => { return usage(&argv[0]); } } } + if optind < argv.len() { + return usage(&argv[0]); + } + buf.resize(wordsize, 0); loop { From ca6865688ad7c9dadc796f1ab3e9a5f249fe6284 Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 8 Jul 2024 13:22:38 -0600 Subject: [PATCH 080/104] swab(1): updates getopt usage --- src/swab.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/swab.rs b/src/swab.rs index 5b4c173..8573cea 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -1,5 +1,6 @@ /* * Copyright (c) 2024 DTB + * Copyright (c) 2024 Emma Tebibyte * SPDX-License-Identifier: AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify it under @@ -54,12 +55,10 @@ fn main() -> ExitCode { while let Some(opt) = argv.getopt(":w:") { match opt.opt() { Ok("w") => { - if let Some(arg) = opt.arg() { - match arg.parse::() { - Ok(w) if w % 2 == 0 => { wordsize = w; () }, + match opt.arg().unwrap().parse::() { + Ok(w) if w % 2 == 0 => { wordsize = w; }, _ => { return usage(&argv[0]); }, } - } optind = opt.ind(); }, _ => { return usage(&argv[0]); } From b7bc1f16ad4047e6eeb1d48c3d1066b69b0b5d3a Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 14:34:42 -0600 Subject: [PATCH 081/104] swab(1): use the getopt error message --- src/swab.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/swab.rs b/src/swab.rs index 8573cea..dd5b464 100644 --- a/src/swab.rs +++ b/src/swab.rs @@ -52,7 +52,7 @@ fn main() -> ExitCode { let mut optind: usize = 1; // argv[0] let mut wordsize: usize = 2; // Equivalent to dd(1p). - while let Some(opt) = argv.getopt(":w:") { + while let Some(opt) = argv.getopt("w:") { match opt.opt() { Ok("w") => { match opt.arg().unwrap().parse::() { From 0df2c9f56696fb16695c77665654d287eb90298e Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 22:48:16 -0600 Subject: [PATCH 082/104] dj(1): fix infiniskipping --- src/dj.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/dj.c b/src/dj.c index 8fe1af3..e36623e 100644 --- a/src/dj.c +++ b/src/dj.c @@ -263,11 +263,11 @@ int main(int argc, char *argv[]){ assert(io[0].bufuse == 0); { /* read */ - char skipping; + long skipping; size_t t; /* hack to intentionally get a partial read from Io_read */ - if((skipping = (io[0].seek > 0)) && io[0].seek < io[0].bs) + if((skipping = MIN(io[0].seek, io[0].bs)) > 0) io[0].bufuse = io[0].bs - io[0].seek; t = io[0].bufuse; @@ -290,7 +290,8 @@ int main(int argc, char *argv[]){ } } - if(skipping){ + if(skipping > 0){ + io[0].seek -= skipping; io[0].bufuse = 0; count += (count != 0); continue; From 8f8de5de2b8e7f59c73a3506f4360071ddae8ae5 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 8 Jul 2024 22:53:44 -0600 Subject: [PATCH 083/104] dj(1): fix io[0].bufuse underflow --- src/dj.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/dj.c b/src/dj.c index e36623e..3b5bc5f 100644 --- a/src/dj.c +++ b/src/dj.c @@ -268,7 +268,7 @@ int main(int argc, char *argv[]){ /* hack to intentionally get a partial read from Io_read */ if((skipping = MIN(io[0].seek, io[0].bs)) > 0) - io[0].bufuse = io[0].bs - io[0].seek; + io[0].bufuse = io[0].bs - (size_t)skipping; t = io[0].bufuse; if(Io_read(&io[0])->bufuse == t && !noerror && io[0].error == 0) From 699893af892788d10f8c4664ae6b08a3f7d4017d Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 03:09:00 -0600 Subject: [PATCH 084/104] intcmp(1): initial rust impl --- src/intcmp.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/intcmp.rs diff --git a/src/intcmp.rs b/src/intcmp.rs new file mode 100644 index 0000000..470e751 --- /dev/null +++ b/src/intcmp.rs @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2023–2024 DTB + * SPDX-License-Identifier: AGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU Affero General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more + * details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see https://www.gnu.org/licenses/. + */ + +// /* 0b00? */ /* Equal | -e | 0b001 | 1 */ +// #define EQUAL 0x01 /* Greater | -g | 0b010 | 2 */ +// /* 0b0?0 */ /* Greater or Equal | -ge | 0b011 | 3 */ +// #define GREATER 0x02 /* Less | -l | 0b100 | 4 */ +// /* 0b?00 */ /* Less or Equal | -le | 0b101 | 5 */ +// #define LESS 0x04 /* Inequal (Greater or Less) | -gl | 0b110 | 6 */ + +use std::{ + env::args, + process::ExitCode +}; + +fn usage(s: &str) -> ExitCode { + eprintln!("Usage: {} [-egl] integer integer...", s); + ExitCode::from(EX_USAGE as u8) +} + +fn main() -> ExitCode { + let argv = args().collect::>(); + let mut can_eq = false; + let mut can_gt = false; + let mut can_lt = false; + let mut optind = 0; + + if argv.len() < 3 { return usage(&argv[0]); } + + while let Some(opt) = argv.getopt("egl") { + match opt.opt() { + Ok("e") => can_eq = true, + Ok("g") => can_gt = true, + Ok("l") => can_lt = true, + _ => { return usage(&argv[0]); }, + } + optind = opt.ind(); + } + + if argv.len() - optind < 2 /* ref cmp */ { return usage(&argv[0]); } + + let mut reference = None; + let mut cmpn: usize; + + for arg in argv.iter().skip(optind) { + match arg.parse::() { + Ok(n) => cmpn = n, + _ => { + eprintln!("{}: {}: Invalid integer", &argv[0], arg); + return ExitCode::from(EX_USAGE as u8); + } + } + + if let Some(refn) = reference { + if (!can_eq && refn == cmpn) + || (!can_gt && refn > cmpn) + || (!can_lt && refn < cmpn) + { return ExitCode::FAILURE; } + } + } + + ExitCode::SUCCESS +} From 2f2270322adb2839c4a18298090624a4db12f36b Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 03:14:57 -0600 Subject: [PATCH 085/104] intcmp(1): rewrite in rust --- Makefile | 4 +-- src/intcmp.c | 82 --------------------------------------------------- src/intcmp.rs | 17 ++++++----- 3 files changed, 11 insertions(+), 92 deletions(-) delete mode 100644 src/intcmp.c diff --git a/Makefile b/Makefile index 5e2c70d..8f1f6d9 100644 --- a/Makefile +++ b/Makefile @@ -109,8 +109,8 @@ build/bin/hru: src/hru.rs build rustlibs .PHONY: intcmp intcmp: build/bin/intcmp -build/bin/intcmp: src/intcmp.c build - $(CC) $(CFLAGS) -o $@ src/intcmp.c +build/bin/intcmp: src/intcmp.rs build rustlibs + $(RUSTC) $(RUSTFLAGS) $(RUSTLIBS) -o $@ src/intcmp.rs .PHONY: mm mm: build/bin/mm diff --git a/src/intcmp.c b/src/intcmp.c deleted file mode 100644 index d6dff0d..0000000 --- a/src/intcmp.c +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2023 DTB - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - */ - -#include /* errno */ -#include /* fprintf(3), stderr */ -#include /* strtol(3), size_t, EXIT_FAILURE */ -#include /* getopt(3), optind */ -#include - -/* 0b00? */ /* Equal | -e | 0b001 | 1 */ -#define EQUAL 0x01 /* Greater | -g | 0b010 | 2 */ -/* 0b0?0 */ /* Greater or Equal | -ge | 0b011 | 3 */ -#define GREATER 0x02 /* Less | -l | 0b100 | 4 */ -/* 0b?00 */ /* Less or Equal | -le | 0b101 | 5 */ -#define LESS 0x04 /* Inequal (Greater or Less) | -gl | 0b110 | 6 */ - -static char *program_name = "intcmp"; - -int main(int argc, char *argv[]){ - int c; - size_t i; - unsigned char mode; - int r; /* reference integer */ - - mode = 0; - - if(argc < 3) - goto usage; - - while((c = getopt(argc, argv, "egl")) != -1) - switch(c){ - case 'e': mode |= EQUAL; break; - case 'g': mode |= GREATER; break; - case 'l': mode |= LESS; break; - default: goto usage; - } - - if(optind + 2 /* ref cmp */ > argc){ -usage: fprintf(stderr, - "Usage: %s [-egl] integer integer...\n", - argv[0] == NULL ? program_name : argv[0]); - return EX_USAGE; - } - - i = optind; - - do{ r = c; - c = strtol(argv[i], &argv[i], 10); - if(*argv[i] != '\0' || errno != 0){ - fprintf(stderr, "%s: argument #%d: Invalid integer\n", - argv[0], (int)i); - return EX_USAGE; - } - - if(i == optind) - continue; - - /* rule enforcement; if a mode isn't permitted and the numbers - * correspond to it, return 1 */ - if( (!(mode & EQUAL) && r == c) - || (!(mode & GREATER) && r > c) - || (!(mode & LESS) && r < c)) - return 1; - }while(++i < argc); - - return 0; -} diff --git a/src/intcmp.rs b/src/intcmp.rs index 470e751..88be72c 100644 --- a/src/intcmp.rs +++ b/src/intcmp.rs @@ -16,18 +16,17 @@ * along with this program. If not, see https://www.gnu.org/licenses/. */ -// /* 0b00? */ /* Equal | -e | 0b001 | 1 */ -// #define EQUAL 0x01 /* Greater | -g | 0b010 | 2 */ -// /* 0b0?0 */ /* Greater or Equal | -ge | 0b011 | 3 */ -// #define GREATER 0x02 /* Less | -l | 0b100 | 4 */ -// /* 0b?00 */ /* Less or Equal | -le | 0b101 | 5 */ -// #define LESS 0x04 /* Inequal (Greater or Less) | -gl | 0b110 | 6 */ - use std::{ env::args, process::ExitCode }; +extern crate getopt; +use getopt::GetOpt; + +extern crate sysexits; +use sysexits::EX_USAGE; + fn usage(s: &str) -> ExitCode { eprintln!("Usage: {} [-egl] integer integer...", s); ExitCode::from(EX_USAGE as u8) @@ -54,7 +53,7 @@ fn main() -> ExitCode { if argv.len() - optind < 2 /* ref cmp */ { return usage(&argv[0]); } - let mut reference = None; + let mut reference: Option = None; let mut cmpn: usize; for arg in argv.iter().skip(optind) { @@ -72,6 +71,8 @@ fn main() -> ExitCode { || (!can_lt && refn < cmpn) { return ExitCode::FAILURE; } } + + reference = Some(cmpn); } ExitCode::SUCCESS From 8d743dab7a2dc32f47c50e7a64e3b93a47730001 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 03:43:25 -0600 Subject: [PATCH 086/104] strcmp(1): add copyright header I could trace strcmp(1) as far back as in my repo. --- src/strcmp.c | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/strcmp.c b/src/strcmp.c index 33b73c2..bd42054 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -1,3 +1,21 @@ +/* + * Copyright (c) 2022–2024 DTB + * SPDX-License-Identifier: AGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU Affero General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more + * details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see https://www.gnu.org/licenses/. + */ + #include /* fprintf(3), stderr */ #include /* EXIT_FAILURE */ #include From 5caefbb465eccdf1062fb6f01cbeecaf31d86d5d Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 03:45:36 -0600 Subject: [PATCH 087/104] strcmp(1): note used sysexit --- src/strcmp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/strcmp.c b/src/strcmp.c index bd42054..f2b86bb 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -18,7 +18,7 @@ #include /* fprintf(3), stderr */ #include /* EXIT_FAILURE */ -#include +#include /* EX_USAGE */ static char *program_name = "strcmp"; From d87c278be5f071f01c3611411c665b92d35ad914 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 04:21:50 -0600 Subject: [PATCH 088/104] strcmp(1): re-style, tweak exits --- src/strcmp.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/strcmp.c b/src/strcmp.c index f2b86bb..7de36a5 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -17,26 +17,26 @@ */ #include /* fprintf(3), stderr */ -#include /* EXIT_FAILURE */ +#include /* size_t */ #include /* EX_USAGE */ -static char *program_name = "strcmp"; +static *program_name = "strcmp"; int main(int argc, char *argv[]){ - int i; - - if(argc < 3){ + if (argc < 3) { fprintf(stderr, "Usage: %s string string...\n", - argv[0] == NULL ? program_name : argv[0]); + argv[0] == NULL ? program_name : argv[0] + ); return EX_USAGE; } - for(; *argv[1] != '\0'; ++argv[1]) - for(i = 2; i < argc; ++i) - if(*argv[i-1] > *argv[i]) - return 1; - else if(*argv[i-1] < *argv[i]++) - return -1; /* actually 255 */ + for (; *argv[1] != '\0'; ++argv[1]) { /* iterate chars in ref */ + /* iterate argc */ + for (size_t i = 2 /* ref cmp */; i < argc; ++argv[i], ++i) { + /* this doesn't overrun because of nul termination */ + if (*argv[i-1] != *argv[i]) { return *argv[i-1] - *argv[i]; } + } + } return 0; } From 16f23e11c0dde95690ed1a2ec969170073493f24 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 04:26:57 -0600 Subject: [PATCH 089/104] strcmp.1: update docs to match utility --- docs/strcmp.1 | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/strcmp.1 b/docs/strcmp.1 index c99c8c8..db6d3e8 100644 --- a/docs/strcmp.1 +++ b/docs/strcmp.1 @@ -4,7 +4,7 @@ .\" This work is licensed under CC BY-SA 4.0. To see a copy of this license, .\" visit . .\" -.TH STRCMP 1 2024-06-17 "Harakit X.X.X" +.TH STRCMP 1 2024-07-15 "Harakit X.X.X" .SH NAME strcmp \(en compare strings .\" @@ -20,15 +20,15 @@ Check whether string arguments are the same. .SH DIAGNOSTICS The program will exit successfully if the strings are identical. Otherwise, it -will exit with an error code of 1 if a string passed has a lesser byte value -than one of the prior strings: +will exit with an error code less than 128 if a string passed has a lesser byte +value than one of the prior strings: .RS strcmp b a .RE -or with an error code of 255 if it has a greater byte value than one of the -prior strings: +or with an error code greater than 128 if it has a greater byte value than one +of the prior strings: .RS strcmp a b From efb3ce626d28f3ae8dea04f22cf54adc713f03a7 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 04:29:43 -0600 Subject: [PATCH 090/104] strcmp(1): fix program_name type --- src/strcmp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/strcmp.c b/src/strcmp.c index 7de36a5..784029c 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -20,7 +20,7 @@ #include /* size_t */ #include /* EX_USAGE */ -static *program_name = "strcmp"; +char *program_name = "strcmp"; int main(int argc, char *argv[]){ if (argc < 3) { From 1b3b03cae093e6e343fb5bf021dd2c303375a3cd Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 13 Jul 2024 23:49:27 -0600 Subject: [PATCH 091/104] mm(1): rewritten in Rust --- Makefile | 4 +- src/mm.c | 236 ------------------------------------------------------ src/mm.rs | 137 +++++++++++++++++++++++++++++++ 3 files changed, 139 insertions(+), 238 deletions(-) delete mode 100644 src/mm.c create mode 100644 src/mm.rs diff --git a/Makefile b/Makefile index 5e2c70d..a523591 100644 --- a/Makefile +++ b/Makefile @@ -114,8 +114,8 @@ build/bin/intcmp: src/intcmp.c build .PHONY: mm mm: build/bin/mm -build/bin/mm: src/mm.c build - $(CC) $(CFLAGS) -o $@ src/mm.c +build/bin/mm: src/mm.rs build rustlibs + $(RUSTC) $(RUSTFLAGS) $(RUSTLIBS) -o $@ src/mm.rs .PHONY: npc npc: build/bin/npc diff --git a/src/mm.c b/src/mm.c deleted file mode 100644 index e905b35..0000000 --- a/src/mm.c +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) 2024 DTB - * SPDX-License-Identifier: AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify it under - * the terms of the GNU Affero General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more - * details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see https://www.gnu.org/licenses/. - */ - -#include /* errno */ -#include /* signal(2), SIG_ERR, SIG_IGN, SIGINT */ -#include /* fclose(3), fopen(3), fprintf(3), getc(3), putc(3), - * setvbuf(3), size_t, _IONBF, NULL */ -#include /* free(3), realloc(3) */ -#include /* strcmp(3), strerror(3) */ -#include /* getopt(3) */ -#if !defined EX_IOERR || !defined EX_OK || !defined EX_OSERR \ - || !defined EX_USAGE -# include -#endif -extern int errno; - -/* This structure is how open files are tracked. */ -struct Files{ - size_t a; /* allocation */ - size_t s; /* used size */ - char *mode; /* file opening mode */ - char **names; /* file names */ - FILE **files; /* file pointers */ -}; - -/* How much to grow the allocation when it's saturated. */ -#ifndef ALLOC_INCREMENT -# define ALLOC_INCREMENT 1 -#endif - -/* How much to grow the allocation at program start. */ -#ifndef ALLOC_INITIAL -# define ALLOC_INITIAL 10 -#endif - -/* pre-allocated strings */ -static char *program_name = ""; -static char *stdin_name = ""; -static char *stdout_name = ""; -static char *stderr_name = ""; -static char *(fmode[]) = { (char []){"rb"}, (char []){"rb+"} }; -static char *wharsh = "wb"; - -/* Adds the open FILE pointer for the file at the path s to the files struct, - * returning the FILE if successful and NULL if not, allocating more memory in - * the files buffers as needed. */ -static FILE * -Files_append(struct Files *files, FILE *file, char *name){ - - if(file == NULL || (files->s == files->a - && ((files->files = realloc(files->files, - (files->a += (files->a == 0) - ? ALLOC_INITIAL - : ALLOC_INCREMENT) - * sizeof *(files->files))) == NULL - || (files->names = realloc(files->names, - files->a * sizeof *(files->names))) == NULL))) - return NULL; - - files->names[files->s] = name; - return files->files[files->s++] = file; -} - -/* Opens the file at the path p and puts it in the files struct, returning NULL - * if either the opening or the placement of the open FILE pointer fail. */ -#define Files_open(files, p) \ - Files_append((files), fopen((p), (files)->mode), (p)) - -/* Prints a diagnostic message based on errno and returns an exit status - * appropriate for an OS error. */ -static int -oserr(char *s, char *r){ - - fprintf(stderr, "%s: %s: %s\n", s, r, strerror(errno)); - - return EX_OSERR; -} - -/* Hijacks i and j from main and destructs the files[2] struct used by main by - * closing its files and freeing its files and names arrays, returning retval - * from main. */ -#define terminate \ - for(i = 0; i < 2; ++i){ \ - for(j = 0; j < files[i].s; ++j) \ - if(files[i].files[j] != stdin \ - && files[i].files[j] != stdout \ - && files[i].files[j] != stderr) \ - fclose(files[i].files[j]); \ - free(files[i].files); \ - free(files[i].names); \ - } \ - return retval - -/* Prints a usage text, in which s is the program being run (i.e. argv[0]), and - * returns an exit status appropriate for a usage error. */ -int usage(char *s){ - - fprintf(stderr, "Usage: %s [-aenu] [-i input]... [-o output]...\n", s); - - return EX_USAGE; -} - -int main(int argc, char *argv[]){ - int c; - struct Files files[2]; /* {read, write} */ - size_t i; - size_t j; - size_t k; /* loop index but also unbuffer status */ - int retval; - - /* Initializes the files structs with their default values, standard - * input and standard output. If an input or an output is specified - * these initial values will be overwritten, so to, say, use mm(1) - * equivalently to tee(1p), -o - will need to be specified before - * additional files to ensure standard output is still written. */ - for(i = 0; i < 2; ++i){ - files[i].a = 0; - files[i].s = 0; - files[i].mode = fmode[i]; - files[i].files = NULL; - files[i].names = NULL; - Files_append(&files[i], i == 0 ? stdin : stdout, - i == 0 ? stdin_name : stdout_name); - files[i].s = 0; - } - - k = 0; - - if(argc > 0) - program_name = argv[0]; - - if(argc > 1) - while((c = getopt(argc, argv, "aehi:no:u")) != -1) - switch(c){ - case 'a': /* "rb+" -> "ab" */ - files[1].mode[0] = 'a'; - files[1].mode[2] = '\0'; - break; - case 'e': - if(Files_append(&files[1], stderr, stderr_name) != NULL) - break; - retval = oserr(argv[0], "-e"); - terminate; - case 'i': - if((strcmp(optarg, "-") == 0 && Files_append(&files[0], - stdin, stdin_name) != NULL) - || Files_open(&files[0], optarg) != NULL) - break; - retval = oserr(argv[0], optarg); - terminate; - case 'o': - if((strcmp(optarg, "-") == 0 && Files_append(&files[1], - stdout, stdout_name) != NULL) - || Files_open(&files[1], optarg) != NULL) - break; - /* does not exist, so try to create it */ - if(errno == ENOENT){ - files[1].mode = wharsh; - if(Files_open(&files[1], optarg) != NULL){ - files[1].mode = fmode[1]; - break; - } - } - retval = oserr(argv[0], optarg); - terminate; - case 'n': - if(signal(SIGINT, SIG_IGN) != SIG_ERR) - break; - retval = oserr(argv[0], "-n"); - terminate; - case 'u': - k = 1; - break; - default: - retval = usage(argv[0]); - terminate; - } - - if(optind != argc){ - retval = usage(argv[0]); - terminate; - } - - files[0].s += files[0].s == 0; - files[1].s += files[1].s == 0; - - /* Unbuffer files. */ - if(k){ - for(i = 0; - i < files[0].s; - setvbuf(files[0].files[i++], NULL, _IONBF, 0)); - for(i = 0; - i < files[1].s; - setvbuf(files[1].files[i++], NULL, _IONBF, 0)); - } - - retval = EX_OK; - - /* Actual program loop. */ - for(i = 0; i < files[0].s; ++i) /* iterate ins */ - while((c = getc(files[0].files[i])) != EOF) /* iterate chars */ - for(j = 0; j < files[1].s; ++j) /* iterate outs */ - if(putc(c, files[1].files[j]) == EOF){ - /* notebook's full */ - retval = EX_IOERR; - fprintf(stderr, "%s: %s: %s\n", - program_name, files[1].names[j], strerror(errno)); - if(fclose(files[1].files[j]) == EOF) - fprintf(stderr, "%s: %s: %s\n", - program_name, files[1].names[j], strerror(errno)); - /* massage out the tense muscle */ - for(k = j--; k < files[1].s - 1; ++k){ - files[1].files[k] = files[1].files[k+1]; - files[1].names[k] = files[1].names[k+1]; - } - if(--files[1].s == 0) - terminate; - } - - terminate; -} diff --git a/src/mm.rs b/src/mm.rs new file mode 100644 index 0000000..aa7ce19 --- /dev/null +++ b/src/mm.rs @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2024 Emma Tebibyte + * SPDX-License-Identifier: AGPL-3.0-or-later + * + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU Affero General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more + * details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see https://www.gnu.org/licenses/. + */ + +use std::{ + env::args, + fs::File, + io::{ stdin, stdout, stderr, BufWriter, Read, Write }, + os::fd::{ AsRawFd, FromRawFd }, + process::{ exit, ExitCode }, +}; + +extern crate getopt; +extern crate strerror; +extern crate sysexits; + +use getopt::GetOpt; +use strerror::StrError; +use sysexits::{ EX_IOERR, EX_USAGE }; + +fn main() -> ExitCode { + let argv = args().collect::>(); + let usage = format!("Usage: {} [-aeu] [-i input] [-o output]", argv[0]); + + let mut a = false; /* append rather than update */ + let mut e = false; /* use stderr as an output */ + let mut u = false; /* unbuffer i/o */ + let mut ins = Vec::new(); /* initial inputs vector */ + let mut outs = Vec::new(); /* initial outputs vector */ + + while let Some(opt) = argv.getopt("aei:o:u") { + match opt.opt() { + Ok("a") => a = true, + Ok("e") => e = true, + Ok("u") => u = true, + Ok("i") => { /* add input */ + let input = opt.arg().unwrap(); + ins.push(input); + }, + Ok("o") => { /* add output */ + let output = opt.arg().unwrap(); + outs.push(output); + }, + Err(_) | Ok(_) => { + eprintln!("{}", usage); + return ExitCode::from(EX_USAGE as u8); + }, + }; + } + + /* use stdin if no inputs are specified */ + if ins.is_empty() { ins.push("-".to_string()); } + + /* use stdout if no outputs are specified */ + if outs.is_empty() { outs.push("-".to_string()); } + + /* map all path strings to files */ + let inputs = ins.iter().map(|file| { + /* if a file is “-”, it is stdin */ + if *file == "-" { + return unsafe { File::from_raw_fd(stdin().as_raw_fd()) }; /* fd0 = stdin */ + } + + match File::options().append(a).open(file) { + Ok(f) => f, + Err(e) => { + eprintln!("{}: {}", argv[0], e.strerror()); + exit(EX_IOERR); + }, + } + }).collect::>(); + + /* map all path strings to files */ + let mut outputs = outs.iter().map(|file| { + /* of a file is “-”, it is stdout */ + if *file == "-" { + return unsafe { File::from_raw_fd(stdout().as_raw_fd()) }; /* fd1 = stdout */ + } + + match File::options().append(a).open(file) { + Ok(f) => return f, + Err(e) => { + eprintln!("{}: {}", argv[0], e.strerror()); + exit(EX_IOERR); + }, + }; + }).collect::>(); + + /* if -e is specified, use stderr */ + if e { + outputs.push(unsafe { File::from_raw_fd(stderr().as_raw_fd()) }); /* fd2 = stderr */ + } + + let mut outputs = outputs.iter().map(|o| { + if u { + BufWriter::with_capacity(0, o) + } else { + BufWriter::new(o) + } + }).collect::>(); + + for file in inputs { + for byte in file.bytes().map(|b| { + b.unwrap_or_else(|e| { + eprintln!("{}: {}", argv[0], e.strerror()); + exit(EX_IOERR); + }) + }) { + for out in &mut outputs { + if let Err(e) = out.write(&[byte]) { + eprintln!("{}: {}", argv[0], e.strerror()); + return ExitCode::from(EX_IOERR as u8); + } + if let Err(e) = out.flush() { + eprintln!("{}: {}", argv[0], e.strerror()); + return ExitCode::from(EX_IOERR as u8); + } + } + } + } + + ExitCode::SUCCESS +} From e972ff468aeee799090477fb9a270ec3f0d7f475 Mon Sep 17 00:00:00 2001 From: emma Date: Sat, 13 Jul 2024 23:56:30 -0600 Subject: [PATCH 092/104] mm(1): added -t for disabling truncation; mm.1: updated docs --- docs/mm.1 | 16 ++++++---------- src/mm.rs | 14 ++++++++------ 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/docs/mm.1 b/docs/mm.1 index 2916aa7..d4659d2 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -10,7 +10,7 @@ mm \(en middleman .SH SYNOPSIS mm -.RB [ -aenu ] +.RB [ -aetu ] .RB [ -i\ input ] .RB [ -o\ output ] .\" @@ -21,19 +21,19 @@ Catenate input files and write them to the start of each output file or stream. .SH OPTIONS .IP \fB-a\fP -Opens subsequent outputs for appending rather than updating. +Opens outputs for appending rather than updating. .IP \fB-e\fP Use the standard error as an output. +.IP \fB-t\fP +Causes outputs to be overwritten instead of being truncated. +.IP \fB-u\fP +Ensures neither input or output will be buffered. .IP \fB-i\fP\ \fIinput\fP Opens a path as an input. If one or more of the input files is \(lq-\(rq or if no inputs are specified, the standard input shall be used. .IP \fB-o\fP\ \fIoutput\fP Opens a path as an output. If one or more of the output files is \(lq-\(rq or if no outputs are specified, the standard output shall be used. -.IP \fB-u\fP -Ensures neither input or output will be buffered. -.IP \fB-n\fP -Causes SIGINT signals to be ignored. .\" .SH DIAGNOSTICS @@ -45,10 +45,6 @@ exits with the appropriate .BR sysexits.h (3) status. .\" -.SH CAVEATS - -Existing files are not truncated on ouput and are instead overwritten. -.\" .SH RATIONALE The diff --git a/src/mm.rs b/src/mm.rs index aa7ce19..e991b5a 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -34,19 +34,21 @@ use sysexits::{ EX_IOERR, EX_USAGE }; fn main() -> ExitCode { let argv = args().collect::>(); - let usage = format!("Usage: {} [-aeu] [-i input] [-o output]", argv[0]); + let usage = format!("Usage: {} [-aetu] [-i input] [-o output]", argv[0]); let mut a = false; /* append rather than update */ let mut e = false; /* use stderr as an output */ + let mut t = true; let mut u = false; /* unbuffer i/o */ let mut ins = Vec::new(); /* initial inputs vector */ let mut outs = Vec::new(); /* initial outputs vector */ - while let Some(opt) = argv.getopt("aei:o:u") { + while let Some(opt) = argv.getopt("aei:o:tu") { match opt.opt() { Ok("a") => a = true, - Ok("e") => e = true, - Ok("u") => u = true, + Ok("e") => e = true, + Ok("u") => u = true, + Ok("t") => t = false, Ok("i") => { /* add input */ let input = opt.arg().unwrap(); ins.push(input); @@ -75,7 +77,7 @@ fn main() -> ExitCode { return unsafe { File::from_raw_fd(stdin().as_raw_fd()) }; /* fd0 = stdin */ } - match File::options().append(a).open(file) { + match File::options().open(file) { Ok(f) => f, Err(e) => { eprintln!("{}: {}", argv[0], e.strerror()); @@ -91,7 +93,7 @@ fn main() -> ExitCode { return unsafe { File::from_raw_fd(stdout().as_raw_fd()) }; /* fd1 = stdout */ } - match File::options().append(a).open(file) { + match File::options().truncate(t).append(a).open(file) { Ok(f) => return f, Err(e) => { eprintln!("{}: {}", argv[0], e.strerror()); From 3b7625459921aebd9b7c37b411fa523fe0bce1b2 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 00:31:23 -0600 Subject: [PATCH 093/104] mm(1): fixes creating files --- src/mm.rs | 42 ++++++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/src/mm.rs b/src/mm.rs index e991b5a..9c1151c 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -36,12 +36,12 @@ fn main() -> ExitCode { let argv = args().collect::>(); let usage = format!("Usage: {} [-aetu] [-i input] [-o output]", argv[0]); - let mut a = false; /* append rather than update */ + let mut a = false; /* append to the file */ let mut e = false; /* use stderr as an output */ - let mut t = true; + let mut t = true; /* do not truncate the file before writing */ let mut u = false; /* unbuffer i/o */ - let mut ins = Vec::new(); /* initial inputs vector */ - let mut outs = Vec::new(); /* initial outputs vector */ + let mut ins = Vec::new(); /* initial input file path vector */ + let mut outs = Vec::new(); /* initial output file path vector */ while let Some(opt) = argv.getopt("aei:o:tu") { match opt.opt() { @@ -74,29 +74,43 @@ fn main() -> ExitCode { let inputs = ins.iter().map(|file| { /* if a file is “-”, it is stdin */ if *file == "-" { - return unsafe { File::from_raw_fd(stdin().as_raw_fd()) }; /* fd0 = stdin */ + /* portable way to access stdin as a file */ + return unsafe { File::from_raw_fd(stdin().as_raw_fd()) }; } - match File::options().open(file) { + match File::open(file) { Ok(f) => f, Err(e) => { - eprintln!("{}: {}", argv[0], e.strerror()); + eprintln!("{}: {}: {}", argv[0], file, e.strerror()); exit(EX_IOERR); }, } }).collect::>(); + println!("{:?}", outs); + /* map all path strings to files */ let mut outputs = outs.iter().map(|file| { /* of a file is “-”, it is stdout */ if *file == "-" { - return unsafe { File::from_raw_fd(stdout().as_raw_fd()) }; /* fd1 = stdout */ + /* portable way to access stdout as a file */ + return unsafe { File::from_raw_fd(stdout().as_raw_fd()) }; } - match File::options().truncate(t).append(a).open(file) { + let options = File::options() + /* truncate if -t is specified and append if -a is specified */ + .truncate(t) + .append(a) + /* enable the ability to create and write to files */ + .create(true) + .write(true) + /* finally, open the file! */ + .open(file); + + match options { Ok(f) => return f, Err(e) => { - eprintln!("{}: {}", argv[0], e.strerror()); + eprintln!("{}: {}: {}", argv[0], file, e.strerror()); exit(EX_IOERR); }, }; @@ -104,13 +118,16 @@ fn main() -> ExitCode { /* if -e is specified, use stderr */ if e { - outputs.push(unsafe { File::from_raw_fd(stderr().as_raw_fd()) }); /* fd2 = stderr */ + /* portable way to access stderr as a file */ + outputs.push(unsafe { File::from_raw_fd(stderr().as_raw_fd()) }); } let mut outputs = outputs.iter().map(|o| { if u { + /* unbuffered writing through a buffer of capacity 0 */ BufWriter::with_capacity(0, o) } else { + /* theoretically buffered writing */ BufWriter::new(o) } }).collect::>(); @@ -127,7 +144,8 @@ fn main() -> ExitCode { eprintln!("{}: {}", argv[0], e.strerror()); return ExitCode::from(EX_IOERR as u8); } - if let Err(e) = out.flush() { + /* immediately flush the output for -u */ + if let Err(e) = out.flush() { eprintln!("{}: {}", argv[0], e.strerror()); return ExitCode::from(EX_IOERR as u8); } From 37804aab6b799db8b60ba4e9f0853cdc7b18f9a6 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 00:33:37 -0600 Subject: [PATCH 094/104] mm(1): fixes comment about flags -a & -t --- src/mm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mm.rs b/src/mm.rs index 9c1151c..9a1590f 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -98,7 +98,7 @@ fn main() -> ExitCode { } let options = File::options() - /* truncate if -t is specified and append if -a is specified */ + /* don’t truncate if -t is specified, append if -a is specified */ .truncate(t) .append(a) /* enable the ability to create and write to files */ From 8d693b66649cd91cf532ec8ad4bd17dcd2e20d33 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 01:25:25 -0600 Subject: [PATCH 095/104] mm(1): removes debug print --- src/mm.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/mm.rs b/src/mm.rs index 9a1590f..d00dfc2 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -87,8 +87,6 @@ fn main() -> ExitCode { } }).collect::>(); - println!("{:?}", outs); - /* map all path strings to files */ let mut outputs = outs.iter().map(|file| { /* of a file is “-”, it is stdout */ From 20692d581a9cd7574e1e3c78e0d9d63f4ec3678a Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 14:15:55 -0600 Subject: [PATCH 096/104] mm(1): makes -e block inferring stdout as an output, mm.1: reflects changes to -e --- docs/mm.1 | 4 +++- src/mm.rs | 13 ++++++++----- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/docs/mm.1 b/docs/mm.1 index d4659d2..9e26420 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -33,7 +33,9 @@ Opens a path as an input. If one or more of the input files is \(lq-\(rq or if no inputs are specified, the standard input shall be used. .IP \fB-o\fP\ \fIoutput\fP Opens a path as an output. If one or more of the output files is \(lq-\(rq or if -no outputs are specified, the standard output shall be used. +no outputs are specified and the +.B -e +option is not specified, the standard output shall be used. .\" .SH DIAGNOSTICS diff --git a/src/mm.rs b/src/mm.rs index d00dfc2..df431db 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -68,7 +68,7 @@ fn main() -> ExitCode { if ins.is_empty() { ins.push("-".to_string()); } /* use stdout if no outputs are specified */ - if outs.is_empty() { outs.push("-".to_string()); } + if outs.is_empty() && !e { outs.push("-".to_string()); } /* map all path strings to files */ let inputs = ins.iter().map(|file| { @@ -142,10 +142,13 @@ fn main() -> ExitCode { eprintln!("{}: {}", argv[0], e.strerror()); return ExitCode::from(EX_IOERR as u8); } - /* immediately flush the output for -u */ - if let Err(e) = out.flush() { - eprintln!("{}: {}", argv[0], e.strerror()); - return ExitCode::from(EX_IOERR as u8); + + if u { + /* immediately flush the output for -u */ + if let Err(e) = out.flush() { + eprintln!("{}: {}", argv[0], e.strerror()); + return ExitCode::from(EX_IOERR as u8); + } } } } From 8dc763f05ebe58487c5569545342cc5a8ee19945 Mon Sep 17 00:00:00 2001 From: DTB Date: Sun, 14 Jul 2024 18:34:08 -0600 Subject: [PATCH 097/104] mm(1): treats trailing arguments as optargs for the last opt --- src/mm.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/mm.rs b/src/mm.rs index df431db..f39b3b2 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -1,5 +1,6 @@ /* * Copyright (c) 2024 Emma Tebibyte + * Copyright (c) 2024 DTB * SPDX-License-Identifier: AGPL-3.0-or-later * * This program is free software: you can redistribute it and/or modify it under @@ -32,6 +33,8 @@ use getopt::GetOpt; use strerror::StrError; use sysexits::{ EX_IOERR, EX_USAGE }; +enum ArgMode{ In, Out } + fn main() -> ExitCode { let argv = args().collect::>(); let usage = format!("Usage: {} [-aetu] [-i input] [-o output]", argv[0]); @@ -42,6 +45,8 @@ fn main() -> ExitCode { let mut u = false; /* unbuffer i/o */ let mut ins = Vec::new(); /* initial input file path vector */ let mut outs = Vec::new(); /* initial output file path vector */ + let mut mode: Option = None; /* mode for positional arguments */ + let mut optind = 0; while let Some(opt) = argv.getopt("aei:o:tu") { match opt.opt() { @@ -49,19 +54,33 @@ fn main() -> ExitCode { Ok("e") => e = true, Ok("u") => u = true, Ok("t") => t = false, - Ok("i") => { /* add input */ + Ok("i") => { /* add inputs */ let input = opt.arg().unwrap(); ins.push(input); + mode = Some(ArgMode::In); }, Ok("o") => { /* add output */ let output = opt.arg().unwrap(); outs.push(output); + mode = Some(ArgMode::Out); }, Err(_) | Ok(_) => { eprintln!("{}", usage); return ExitCode::from(EX_USAGE as u8); }, }; + optind = opt.ind(); + } + + let remaining = argv.iter().skip(optind); + + if let Some(m) = mode { + for arg in remaining { + match m { + ArgMode::In => ins.push(arg.to_string()), + ArgMode::Out => outs.push(arg.to_string()), + }; + } } /* use stdin if no inputs are specified */ From 7a0ad7800091afce5cf8d84bb44ab7a0abad5d4c Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 18:38:02 -0600 Subject: [PATCH 098/104] mm.1: reflects new changes --- docs/mm.1 | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/mm.1 b/docs/mm.1 index 9e26420..5a90aa1 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -3,7 +3,7 @@ .\" This work is licensed under CC BY-SA 4.0. To see a copy of this license, .\" visit . .\" -.TH MM 1 2024-06-17 "Harakit X.X.X" +.TH MM 1 2024-07-14 "Harakit X.X.X" .SH NAME mm \(en middleman .\" @@ -30,12 +30,16 @@ Causes outputs to be overwritten instead of being truncated. Ensures neither input or output will be buffered. .IP \fB-i\fP\ \fIinput\fP Opens a path as an input. If one or more of the input files is \(lq-\(rq or if -no inputs are specified, the standard input shall be used. +no inputs are specified, the standard input shall be used. If specified as the +last option and if there are trailing arguments to the program, they shall be +appended to the list of files to use as inputs. .IP \fB-o\fP\ \fIoutput\fP Opens a path as an output. If one or more of the output files is \(lq-\(rq or if no outputs are specified and the .B -e -option is not specified, the standard output shall be used. +option is not specified, the standard output shall be used. If specified as the +last option and if there are trailing arguments to the program, they shall be +appended to the list of files to use as inputs. .\" .SH DIAGNOSTICS From eda5385058280f84daa450ddd0a48f64fef52434 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 18:38:53 -0600 Subject: [PATCH 099/104] mm.1: small correction --- docs/mm.1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mm.1 b/docs/mm.1 index 5a90aa1..f641156 100644 --- a/docs/mm.1 +++ b/docs/mm.1 @@ -39,7 +39,7 @@ no outputs are specified and the .B -e option is not specified, the standard output shall be used. If specified as the last option and if there are trailing arguments to the program, they shall be -appended to the list of files to use as inputs. +appended to the list of files to use as outputs. .\" .SH DIAGNOSTICS From 64f3f73d96814cb708bcf69743254a317803f16b Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 18:39:55 -0600 Subject: [PATCH 100/104] mm(1): formatting --- src/mm.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mm.rs b/src/mm.rs index f39b3b2..bb7b3d0 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -33,7 +33,7 @@ use getopt::GetOpt; use strerror::StrError; use sysexits::{ EX_IOERR, EX_USAGE }; -enum ArgMode{ In, Out } +enum ArgMode { In, Out } fn main() -> ExitCode { let argv = args().collect::>(); From 48dbea0228f19b5442fd3cea92918f20d4c14ff4 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 18:41:18 -0600 Subject: [PATCH 101/104] mm(1): imports full enum --- src/mm.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/mm.rs b/src/mm.rs index bb7b3d0..301ed55 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -33,6 +33,8 @@ use getopt::GetOpt; use strerror::StrError; use sysexits::{ EX_IOERR, EX_USAGE }; +use ArgMode::*; + enum ArgMode { In, Out } fn main() -> ExitCode { @@ -57,12 +59,12 @@ fn main() -> ExitCode { Ok("i") => { /* add inputs */ let input = opt.arg().unwrap(); ins.push(input); - mode = Some(ArgMode::In); + mode = Some(In); }, Ok("o") => { /* add output */ let output = opt.arg().unwrap(); outs.push(output); - mode = Some(ArgMode::Out); + mode = Some(Out); }, Err(_) | Ok(_) => { eprintln!("{}", usage); @@ -77,8 +79,8 @@ fn main() -> ExitCode { if let Some(m) = mode { for arg in remaining { match m { - ArgMode::In => ins.push(arg.to_string()), - ArgMode::Out => outs.push(arg.to_string()), + In => ins.push(arg.to_string()), + Out => outs.push(arg.to_string()), }; } } From e7a6632b41d93d361750fd6242d7b0826068cfc4 Mon Sep 17 00:00:00 2001 From: emma Date: Sun, 14 Jul 2024 18:56:23 -0600 Subject: [PATCH 102/104] mm(1): improves comments --- src/mm.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/mm.rs b/src/mm.rs index 301ed55..41b7857 100644 --- a/src/mm.rs +++ b/src/mm.rs @@ -47,7 +47,7 @@ fn main() -> ExitCode { let mut u = false; /* unbuffer i/o */ let mut ins = Vec::new(); /* initial input file path vector */ let mut outs = Vec::new(); /* initial output file path vector */ - let mut mode: Option = None; /* mode for positional arguments */ + let mut mode: Option = None; /* mode set by last-used option */ let mut optind = 0; while let Some(opt) = argv.getopt("aei:o:tu") { @@ -59,30 +59,36 @@ fn main() -> ExitCode { Ok("i") => { /* add inputs */ let input = opt.arg().unwrap(); ins.push(input); - mode = Some(In); + mode = Some(In); /* latest argument == -i */ }, Ok("o") => { /* add output */ let output = opt.arg().unwrap(); outs.push(output); - mode = Some(Out); + mode = Some(Out); /* latest argument == -o */ }, Err(_) | Ok(_) => { eprintln!("{}", usage); return ExitCode::from(EX_USAGE as u8); }, }; + optind = opt.ind(); } let remaining = argv.iter().skip(optind); + /* check the last flag specified */ if let Some(m) = mode { for arg in remaining { + /* move the subsequent arguments to the list of inputs or outputs */ match m { In => ins.push(arg.to_string()), Out => outs.push(arg.to_string()), }; } + } else { + eprintln!("{}", usage); + return ExitCode::from(EX_USAGE as u8); } /* use stdin if no inputs are specified */ From becb3bac4eb308584ab13f558fe17e692cc8f8bb Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 14:40:26 -0600 Subject: [PATCH 103/104] strcmp(1): code clarification --- src/strcmp.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/strcmp.c b/src/strcmp.c index 784029c..33eab10 100644 --- a/src/strcmp.c +++ b/src/strcmp.c @@ -30,10 +30,11 @@ int main(int argc, char *argv[]){ return EX_USAGE; } - for (; *argv[1] != '\0'; ++argv[1]) { /* iterate chars in ref */ - /* iterate argc */ - for (size_t i = 2 /* ref cmp */; i < argc; ++argv[i], ++i) { - /* this doesn't overrun because of nul termination */ + /* This compares the Nth character of arg[2] onward with argv[1]'s Nth + * character, rather than comparing each arg with argv[1] sequentially. */ + for (; *argv[1] != '\0'; ++argv[1]) { /* iterate chars in argv[1] */ + for (size_t i = 2; i < argc; ++argv[i], ++i) { /* iterate &argv[2] */ + /* this never overruns because of nul termination */ if (*argv[i-1] != *argv[i]) { return *argv[i-1] - *argv[i]; } } } From 27ff64dffabd38555524fdd5b2838af7ec7cc5a4 Mon Sep 17 00:00:00 2001 From: DTB Date: Mon, 15 Jul 2024 14:51:54 -0600 Subject: [PATCH 104/104] intcmp(1): add comments --- src/intcmp.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/intcmp.rs b/src/intcmp.rs index 88be72c..f504b50 100644 --- a/src/intcmp.rs +++ b/src/intcmp.rs @@ -34,45 +34,45 @@ fn usage(s: &str) -> ExitCode { fn main() -> ExitCode { let argv = args().collect::>(); - let mut can_eq = false; - let mut can_gt = false; - let mut can_lt = false; + let mut e = false; /* args can be == */ + let mut g = false; /* args can be > */ + let mut l = false; /* args can be < */ let mut optind = 0; if argv.len() < 3 { return usage(&argv[0]); } while let Some(opt) = argv.getopt("egl") { match opt.opt() { - Ok("e") => can_eq = true, - Ok("g") => can_gt = true, - Ok("l") => can_lt = true, + Ok("e") => e = true, + Ok("g") => g = true, + Ok("l") => l = true, _ => { return usage(&argv[0]); }, } optind = opt.ind(); } - if argv.len() - optind < 2 /* ref cmp */ { return usage(&argv[0]); } + if argv.len() - optind < 2 /* see usage */ { return usage(&argv[0]); } - let mut reference: Option = None; - let mut cmpn: usize; + let mut prev: Option = None; /* no previous operand */ + let mut currn: usize; - for arg in argv.iter().skip(optind) { - match arg.parse::() { - Ok(n) => cmpn = n, + for arg in argv.iter().skip(optind) { /* iterate operands */ + match arg.parse::() { /* parse current operand */ + Ok(n) => currn = n, _ => { eprintln!("{}: {}: Invalid integer", &argv[0], arg); return ExitCode::from(EX_USAGE as u8); } } - if let Some(refn) = reference { - if (!can_eq && refn == cmpn) - || (!can_gt && refn > cmpn) - || (!can_lt && refn < cmpn) + if let Some(prevn) = prev { /* if there was a previous opr., test */ + if (!e && prevn == currn) + || (!g && prevn > currn) + || (!l && prevn < currn) { return ExitCode::FAILURE; } } - reference = Some(cmpn); + prev = Some(currn); /* there is a previous operand */ } ExitCode::SUCCESS