3 ms·
Let's implement buffered, formatted output
- zzo38computer 4y ago"Print-is-append" is something that I had done, in both ways, because it does make sense obviously. In C, you can use open_memstream to make a variable size buffer to append to, similarly than they have there, and you can use any of the existing functions such as fwrite, fputc, fprintf, etc to write to it. If you want to do your own things with it instead of a buffer accumulation, you can use fopencookie. You do not need to do what is shown in that linked document because C already has such a thing; you can use the FILE object for many kind of streams, both built-in and custom streams. (However, custom streams is a GNU feature, so is not standard C, but it is useful sometimes.) (I made a library to compute cryptographic hashes, which does use fopencookie and allows to specify a "echo stream", which if specified also copies the data to another stream too. This way, you can write data to a file or other stream and also compute the hash at the same time, without needing to store it in memory.)
- camel-cdr 4y agoI found that instead of adding format specifiers, one can create a construct that uses occurrences of '\0' in strings to insert values: FMT_BEGIN("a + b = \0 + \0 = \0\n") { FMT(float, (a)); FMT(float, (b)); FMT(float, (a + b)); } FMT_END; FMT_BEGIN("x = \0 = 0x\0 = 0b\0\na = \0\nb = \0\n") { FMT(uint, (x)); FMT(uint_base, ((unsigned)x, 16, "0123456789abcdef")); FMT(uint_base, ((unsigned)x, 2, "01")); FMT(Vec3, (a)); FMT(Vec3, (b)); } FMT_END; The major advantage here is that you don't need to parse a dsl, and you can still have formatting options. A final api would probably use automatic compound literal struct arguments to implement default arguments with names parameters. Type detection should also be possible, although you would need to register all print functions in a global macro. This is just a proof of concept: https://github.com/camel-cdr/cauldron/blob/main/ideas/fmt.c https://github.com/camel-cdr/cauldron/blob/main/ideas/fmt.c