Files

108 lines
2.7 KiB
C

/*
* Copyright (c) 2026 Emma Tebibyte <emma@tebibyte.media>
* 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 <stdio.h> /* putchar(3) */
#include <stdlib.h> /* EXIT_SUCCESS, NULL, strtol(3) */
#include <string.h> /* strcmp(3) */
#ifdef __OpenBSD__
# include <unistd.h> /* pledge(3) */
#endif
#include "tebibase.h" /* merr(3) */
int
main(int argc, char *argv[])
{
int i = 0;
int n;
#ifdef __OpenBSD__
if (pledge("stdio", NULL) == -1) { merr("pledge"); }
#endif
for (n = 1; n < argc; i++) {
switch (argv[1][i]) {
case '\0':
argv[1][i] = ' ';
n++;
i--;
break;
case '\\': /* XSI-conformance */
switch (argv[1][++i]) {
case 'a': /* FALLTHROUGH */
case 'b': /* FALLTHROUGH */
case 'f':
argv[1][i] = argv[1][i] - 0x5a;
break;
case 't': /* FALLTHROUGH */
case 'v':
argv[1][i] = argv[1][i] - 0x6b;
break;
case 'n':
argv[1][i] = '\n';
break;
case 'r':
argv[1][i] = '\r';
break;
case '0': {
int c;
int d = 0;
char oct[4] = { '\0' };
do {
c = argv[1][++i];
oct[d] = c;
d++;
/* bounds check to make sure 0 <= c < 8 */
} while (c > 0x2f && c < 0x38 && d < 4);
i--;
/* if oct[0] failed the bounds check in the do-while,
* the resulting character is still present; this is
* fine because strtol(3) returns 0 if unable to
* convert and '\0' is printed
*
* safe cast to int, max three-digit octal is tiny */
argv[1][i] = (int)strtol(oct, NULL, 8);
break;
}
case 'c': /* Suppress the <newline> that otherwise follows
* the final argument in the output. All
* characters following the '\c' in the arguments
* shall be ignored. */
return EXIT_SUCCESS;
case '\\': /* FALLTHROUGH */
default:
if (argv[1][i] == '\0') {
i--;
}
/* FALLTHROUGH */
}
/* FALLTHROUGH */
default:
(void)putchar(argv[1][i]);
break;
}
}
(void)putchar('\n');
return EXIT_SUCCESS;
}