commit 4d5ea9c

uint  ·  2026-08-07 18:27:03 +0000 UTC
parent a1170e0
PNG: Return ulepng struct by value on init
3 files changed,  +36, -27
+9, -3
 1@@ -5,7 +5,10 @@
 2 
 3 typedef enum {
 4 	ULEPNG_ERR_NONE,
 5-	ULEPNG_ERR_OOM, /* Out of memory */
 6+	ULEPNG_ERR_FAIL,
 7+
 8+	ULEPNG_ERR_FOPEN,
 9+	ULEPNG_ERR_OOM,
10 
11 	ULEPNG_ERR_LAST
12 } UlePNGErr;
13@@ -16,8 +19,11 @@ typedef struct {
14 	UlePNGErr      err;
15 } ulepng;
16 
17-ulepng* ulepng_init(void);
18-ulepng* ulepng_load_file(const char* path);
19+/* Initialise a ulepng with 0 values */
20+ulepng ulepng_init(void);
21+
22+/* Initialise a ulepng with an image loaded from disk */
23+ulepng ulepng_init_file(const char* path);
24 
25 #endif /* ULEPNG_H */
26 
+13, -17
 1@@ -3,39 +3,35 @@
 2 
 3 #include "ulepng.h"
 4 
 5-ulepng* ulepng_init(void)
 6+ulepng ulepng_init(void)
 7 {
 8-	ulepng* png = malloc(sizeof(ulepng));
 9-	if (png == NULL)
10-		return NULL;
11-
12-	png->data = NULL;
13-	png->size = 0;
14-
15+	ulepng png = { NULL, 0, ULEPNG_ERR_NONE };
16 	return png;
17 }
18 
19-ulepng* ulepng_load_file(const char* path)
20+ulepng ulepng_init_file(const char* path)
21 {
22-	ulepng* png = ulepng_init();
23+	ulepng png = ulepng_init();
24 	FILE* file = NULL;
25 
26 	file = fopen(path, "rb");
27-	if (file == NULL)
28-		return NULL;
29+	if (file == NULL) {
30+		png.err = ULEPNG_ERR_FOPEN;
31+		return png;
32+	}
33 
34 	/* get file size */
35 	fseek(file, 0L, SEEK_END);
36-	png->size = ftell(file);
37+	png.size = ftell(file);
38 	rewind(file);
39 
40-	png->data = malloc(png->size);
41-	if (png->data == NULL) {
42-		png->err = ULEPNG_ERR_OOM;
43+	png.data = malloc(png.size);
44+	if (png.data == NULL) {
45+		png.err = ULEPNG_ERR_OOM;
46 		goto cleanup;
47 	}
48 
49-	fread(png->data, 1, png->size, file);
50+	fread(png.data, 1, png.size, file);
51 
52 cleanup:
53 	fclose(file);
+14, -7
 1@@ -1,24 +1,31 @@
 2 #include <stdio.h>
 3+#include <stdlib.h>
 4 
 5 #include "ulepng.h"
 6 
 7 int main(int argc, char* argv[])
 8 {
 9-	ulepng* png;
10+	ulepng png;
11 	unsigned char* x;
12 	unsigned char* diff;
13 
14-	if (argc < 2)
15-		return 1;
16+	if (argc < 2) {
17+		fprintf(stderr, "Provide an argument (path to image)\n");
18+		return EXIT_FAILURE;
19+	}
20 
21-	png = ulepng_load_file(argv[1]);
22+	png = ulepng_init_file(argv[1]);
23+	if (png.err != ULEPNG_ERR_NONE) {
24+		fprintf(stderr, "Failed to open PNG file [ERR: %d]\n", png.err);
25+		return png.err;
26+	}
27 
28-	diff = png->data + png->size;
29-	for (x = png->data; x < diff; x++)
30+	diff = png.data + png.size;
31+	for (x = png.data; x < diff; x++)
32 		printf("%x", *x);
33 
34 	printf("\n");
35 
36-	return 0;
37+	return EXIT_SUCCESS;
38 }
39