From ba3607102263c73af18105902a8e50063618bd96 Mon Sep 17 00:00:00 2001 From: Colin Leroy-Mira Date: Tue, 30 Jan 2024 17:51:00 +0100 Subject: [PATCH] Rewrite fputs in assembly -28 bytes, -1% cycles --- libsrc/common/fputs.c | 28 ---------------------------- libsrc/common/fputs.s | 42 ++++++++++++++++++++++++++++++++++++++++++ test/ref/test_fputs.c | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 28 deletions(-) delete mode 100644 libsrc/common/fputs.c create mode 100644 libsrc/common/fputs.s create mode 100644 test/ref/test_fputs.c diff --git a/libsrc/common/fputs.c b/libsrc/common/fputs.c deleted file mode 100644 index be476a3f0..000000000 --- a/libsrc/common/fputs.c +++ /dev/null @@ -1,28 +0,0 @@ -/* -** int fputs (const char* s, FILE* f); -** -** Ullrich von Bassewitz, 11.08.1998 -*/ - - - -#include -#include -#include -#include "_file.h" - - - -int __fastcall__ fputs (const char* s, register FILE* f) -{ - /* Check if the file is open or if there is an error condition */ - if ((f->f_flags & _FOPEN) == 0 || (f->f_flags & (_FERROR | _FEOF)) != 0) { - return EOF; - } - - /* Write the string */ - return write (f->f_fd, s, strlen (s)); -} - - - diff --git a/libsrc/common/fputs.s b/libsrc/common/fputs.s new file mode 100644 index 000000000..e70374058 --- /dev/null +++ b/libsrc/common/fputs.s @@ -0,0 +1,42 @@ +; +; Colin Leroy-Mira, 2024 +; +; int __fastcall__ fputs (const char* s, register FILE* f) +; + + .export _fputs + .importzp ptr1, ptr2 + .import _write, _strlen + .import swapstk, pushax, returnFFFF + + .include "stdio.inc" + .include "_file.inc" + +_fputs: + sta ptr1 + stx ptr1+1 + + ldy #_FILE::f_flags + lda (ptr1),y + tax + and #_FOPEN ; Check for file open + beq ret_eof + txa + and #(_FERROR|_FEOF); Check for error/eof + bne ret_eof + + ; Push _write parameters + ldy #_FILE::f_fd + lda (ptr1),y + ldx #$00 + jsr swapstk ; Push fd, get s + + jsr pushax ; Push s + + jsr _strlen ; Get length + + ; Write + jmp _write + +ret_eof: + jmp returnFFFF diff --git a/test/ref/test_fputs.c b/test/ref/test_fputs.c new file mode 100644 index 000000000..ad0552317 --- /dev/null +++ b/test/ref/test_fputs.c @@ -0,0 +1,40 @@ +/* + !!DESCRIPTION!! fgets test + !!LICENCE!! Public domain +*/ + +#include "common.h" + +#include +#include +#include +#include +#include +#include + +FILE *in, *out; +char buf[512], err; + +#define INFILE "cf.in" + +int main(int argc,char **argv) +{ + in = fopen(INFILE, "rb"); + if (in == NULL) { + return EXIT_FAILURE; + } + + strcpy(buf, "test"); + if (fputs(buf, in) != EOF) { + printf("Error: can fputs to a file opened for reading\n"); + return EXIT_FAILURE; + } + clearerr(in); + + while (fgets(buf, 512, in) != NULL) { + fputs(buf, stdout); + } + + fclose(in); + return 0; +}