From 76a7cf830eceafac266548bb3802a0cf9b42161a Mon Sep 17 00:00:00 2001 From: Dylan Lom Date: Wed, 17 Feb 2021 22:35:31 +1100 Subject: [PATCH] Add truthy --- Makefile | 5 +++- src/truthy.c | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 src/truthy.c diff --git a/Makefile b/Makefile index b306da3..144a35b 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ DISTMAN = $(DISTDIR)/usr/share/man all: djl-utils.deb dist: bin DEBIAN.control -bin: line sign pasta suptime countdown stopwatch timestamp +bin: line sign pasta suptime countdown truthy stopwatch timestamp distdir: mkdir -p $(DISTBIN) @@ -24,6 +24,9 @@ sign: $(SRCDIR)/sign $(SRCDIR)/sign.1 distdir pasta: $(SRCDIR)/pasta distdir cp $(SRCDIR)/pasta $(DISTBIN)/pasta +truthy: $(SRCDIR)/truthy.c distdir + cc -o $(DISTBIN)/truthy $(SRCDIR)/truthy.c + suptime: $(SRCDIR)/suptime.c $(SRCDIR)/suptime.1 distdir cc -o $(DISTBIN)/suptime $(SRCDIR)/suptime.c cp $(SRCDIR)/suptime.1 $(DISTMAN)/man1/suptime.1 diff --git a/src/truthy.c b/src/truthy.c new file mode 100644 index 0000000..0ed8897 --- /dev/null +++ b/src/truthy.c @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Dylan Lom + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include +#include +#include +#include +#include + +#include "util.h" + +const char *argv0; + +/* + * Check if s is a valid decimal number. + */ +bool +isnum(const char *s) +{ + if (*s == '-' || *s == '+') s++; + while (*s) { + if (!isdigit(*s)) return false; + s++; + } + return true; +} + +/* + * Coalesce s into true/false boolean. + * The following strings are considered false: + * false, null, 0 (and its other representations, e.g. 000, -, +) + * BUG: Non base-10 representations of 0 are considered truthy + */ +bool +truthy(const char *s) +{ + if (isnum(s) && atoi(s) == 0) return false; + if (strcasecmp(s, "false") == 0 || strcasecmp(s, "null") == 0) return false; + + return true; +} + +/* + * Determine if a value is true-adjacent. Inspired by (but not following) + * JavaScript's concept of truthy/falsey-ness. + * https://developer.mozilla.org/en-US/docs/Glossary/Falsy + */ +int +main(int argc, char *argv[]) +{ + SET_ARGV0(); + + if (argc < 1 || !truthy(argv[0])) + return 1; + return 0; +}