logo

utils-std

Collection of commonly available Unix tools
commit: a684ae14e6f69ad53bd11f5a4ff84a816bccf047
parent 615c8fdb57fba2630113e3c126af4c7996fec356
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Thu, 14 Mar 2024 19:16:42 +0100

cmd/seq: split absolute function to lib/absu.h

Diffstat:

MMakefile4++++
Mcmd/seq.c25+++++++------------------
Alib/absu.h36++++++++++++++++++++++++++++++++++++
3 files changed, 47 insertions(+), 18 deletions(-)

diff --git a/Makefile b/Makefile @@ -83,3 +83,7 @@ cmd/df: cmd/df.c lib/humanize.c Makefile cmd/chmod: cmd/chmod.c lib/mode.c lib/symbolize_mode.c Makefile rm -f ${<:=.gcov} ${@:=.gcda} ${@:=.gcno} $(CC) -std=c99 $(CFLAGS) -o $@ cmd/chmod.c lib/mode.c lib/symbolize_mode.c $(LDFLAGS) $(LDSTATIC) + +cmd/seq: cmd/seq.c lib/absu.h Makefile + rm -f ${<:=.gcov} ${@:=.gcda} ${@:=.gcno} + $(CC) -std=c99 $(CFLAGS) -o $@ cmd/seq.c $(LDFLAGS) $(LDSTATIC) diff --git a/cmd/seq.c b/cmd/seq.c @@ -3,6 +3,8 @@ // SPDX-License-Identifier: MPL-2.0 #define _POSIX_C_SOURCE 200809L +#include "../lib/absu.h" + #include <errno.h> // errno #include <stdbool.h> // bool, true, false #include <stdio.h> // puts, fprintf @@ -13,7 +15,7 @@ char *separator = "\n"; bool zero_pad = false; void -seq(long i, long step, long last) +seq(long i, unsigned long step, long last) { if(i == last) { @@ -31,19 +33,6 @@ seq(long i, long step, long last) } } -static long unsigned int -safe_labs(long int a) -{ - if(a >= 0) - { - return (long unsigned int)a; - } - else - { - return (long unsigned int)-a; - } -} - long get_num(char *str) { @@ -91,9 +80,9 @@ main(int argc, char *argv[]) argc -= optind; argv += optind; - long first = 1; - long step = 1; - long last = 1; + long first = 1; + unsigned long step = 1; + long last = 1; switch(argc) { @@ -106,7 +95,7 @@ main(int argc, char *argv[]) break; case 3: first = get_num(argv[0]); - step = (long)safe_labs(get_num(argv[1])); + step = labsu(get_num(argv[1])); last = get_num(argv[2]); break; default: diff --git a/lib/absu.h b/lib/absu.h @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me> +// SPDX-License-Identifier: CC0-1.0 OR WTFPL + +// unsigned by definition reclaims the sign bit of their associated +// signed representation, meaning you can always represent the absolute +// values in an unsigned, even in two's complement where keeping +// a signed representation would cause an error. +// +// Sadly the abs() family of functions in <stdint.h> is misdesigned + +extern unsigned int +absu(int a) +{ + if(a >= 0) + return (unsigned int)a; + else + return (unsigned int)-a; +} + +extern long unsigned int +labsu(long int a) +{ + if(a >= 0) + return (long unsigned int)a; + else + return (long unsigned int)-a; +} + +extern long long unsigned int +llabsu(long long int a) +{ + if(a >= 0) + return (long long unsigned int)a; + else + return (long long unsigned int)-a; +}