[wiki] [sites] Improve the invert.c example || FRIGN
commit 394133dbfc215bb86f80c9419f54d119b009178f
Author: FRIGN <dev_AT_frign.de>
Date: Tue Mar 15 09:37:48 2016 +0100
Improve the invert.c example
Use the best practices(tm) inherited from the codebase. This brings
around 75% speed improvement.
Also avoid unaligned memory accesses while reading the header by reading
in uint32_t instead of uint8_t.
diff --git a/tools.suckless.org/farbfeld/invert.c b/tools.suckless.org/farbfeld/invert.c
index 2e6f67a..de6b875 100644
--- a/tools.suckless.org/farbfeld/invert.c
+++ b/tools.suckless.org/farbfeld/invert.c
_AT_@ -12,40 +12,44 @@
int
main(int argc, char *argv[])
{
- uint32_t width, height, i, j, k;
- uint16_t rgba[4];
- uint8_t hdr[strlen("farbfeld") + 2 * sizeof(uint32_t)];
+ uint64_t rowlen;
+ uint32_t hdr[4], width, height, i, j;
+ uint16_t *row, *rgba;
if (argc > 1) {
fprintf(stderr, "usage: %s
", argv[0]);
return 1;
}
- if (fread(hdr, 1, sizeof(hdr), stdin) != sizeof(hdr)) {
- fprintf(stderr, "incomplete header
");
+ if (fread(hdr, sizeof(uint32_t), 4, stdin) != 4) {
+ fprintf(stderr, "%s: fread error
", argv[0]);
return 1;
}
- if (memcmp("farbfeld", hdr, strlen("farbfeld"))) {
- fprintf(stderr, "invalid magic
");
+ if (memcmp("farbfeld", hdr, sizeof("farbfeld") - 1)) {
+ fprintf(stderr, "%s: invalid magic value
", argv[0]);
return 1;
}
- width = ntohl(*((uint32_t *)(hdr + 8)));
- height = ntohl(*((uint32_t *)(hdr + 12)));
+ width = ntohl(hdr[2]);
+ height = ntohl(hdr[3]);
- if (fwrite(hdr, 1, sizeof(hdr), stdout) != sizeof(hdr)) {
- fprintf(stderr, "write error
");
+ if (fwrite(hdr, sizeof(uint32_t), 4, stdout) != 4) {
+ fprintf(stderr, "%s: fwrite error
", argv[0]);
return 1;
}
+ rowlen = (sizeof("RGBA") - 1) * width;
+ if (!(row = malloc(rowlen * sizeof(uint16_t)))) {
+ fprintf(stderr, "%s: malloc: out of memory
", argv[0]);
+ return 1;
+ }
for (i = 0; i < height; i++) {
- for (j = 0; j < width; j++) {
- if (fread(rgba, sizeof(uint16_t), 4,
- stdin) != 4) {
- fprintf(stderr, "unexpected EOF
");
- return 1;
- }
- for (k = 0; k < 4; k++) {
- rgba[k] = ntohs(rgba[k]);
+ if (fread(row, sizeof(uint16_t), rowlen, stdin) != rowlen) {
+ fprintf(stderr, "%s: fread error
", argv[0]);
+ return 1;
+ }
+ for (rgba = row; (rgba - row) < rowlen; rgba += 4) {
+ for (j = 0; j < 4; j++) {
+ rgba[j] = ntohs(rgba[j]);
}
/* invert colors */
_AT_@ -53,15 +57,14 @@ main(int argc, char *argv[])
rgba[1] = 65535 - rgba[1];
rgba[2] = 65535 - rgba[2];
- for (k = 0; k < 4; k++) {
- rgba[k] = htons(rgba[k]);
- }
- if (fwrite(rgba, sizeof(uint16_t), 4,
- stdout) != 4) {
- fprintf(stderr, "write error
");
- return 1;
+ for (j = 0; j < 4; j++) {
+ rgba[j] = htons(rgba[j]);
}
}
+ if (fwrite(row, sizeof(uint16_t), rowlen, stdout) != rowlen) {
+ fprintf(stderr, "%s: fwrite error
", argv[0]);
+ return 1;
+ }
}
return 0;
Received on Tue Mar 15 2016 - 09:39:16 CET
This archive was generated by hypermail 2.3.0
: Tue Mar 15 2016 - 09:48:19 CET