style. I don't know how to write it without using sprintf and fwrite, and I figured memcpy was harmless, so those are still in there. Do you think this is better? Do you code without using sprintf?
#include <stdlib.h>
#include <stdio.h>
#include "app/src/chibits.h" // for s8 and typedefs, etc.
#include <string.h> // for memcpy
typedef struct {
size beginI, endI;
} Region;
// Assumes UTF-8 or ISO-8859-1 (latin)
static inline bool isGraphChr(u8 ro chr) {
return (chr >= '!' && chr <= '~') || chr > 0xA0;
}
#define s8alloc(size) \
(s8) { (u8[size]) { }, 0 }
static inline void s8write(s8 ro s, FILE * ro stream) {
fwrite(s.data, 1, s.len, stream);
}
static inline void s8sub(
s8 * ro dest,
s8 ro src,
size ro from,
size ro len) {
memcpy(dest->data + dest->len, src.data + from, len);
dest->len += len;
}
int main(void) {
// Example data
s8 ro str = s8(
"Once upon a time in a land far far away there was a strange and vast forest");
// Storage
i8 nWords = 0;
size ro nWordRegions = 30;
Region wordRegions[nWordRegions];
// Find the words
{
bool inWord = false;
size i = 0;
for (; i < str.len; i++) {
if (inWord) {
if (isGraphChr(str.data[i])) { continue; }
inWord = false;
wordRegions[nWords - 1].endI = i;
continue;
}
if (isGraphChr(str.data[i])) {
if (nWords > nWordRegions) {
fprintf(stderr, "Reached word region storage limit");
return EXIT_FAILURE;
}
inWord = true;
wordRegions[nWords++].beginI = i;
continue;
}
}
if (inWord) { wordRegions[nWords - 1].endI = i; }
}
// Format output
s8 outp = s8alloc(2000); // this number here is just a complete guess
for (i8 i = 0; i < nWords; i++) {
Region ro wr = wordRegions[i];
size ro wordLen = wr.endI - wr.beginI;
int lnLen; // has to be int otherwise warnings
sprintf(
outp.data + outp.len,
"%" PRIi8 ": From %ld to %ld (length %ld): %n",
i,
wr.beginI,
wr.endI,
wordLen,
&lnLen);
outp.len += lnLen;
s8sub(&outp, str, wr.beginI, wordLen);
outp.data[outp.len++] = '\n';
}
s8write(outp, stdout);
return EXIT_SUCCESS;
}
looks slightly better to me, although I'm not so sure how sound s8alloc is
Обсуждают сегодня