[pacman-dev] [PATCH] Optimize _alpm_archive_fgets with an internal buffer.

Chantry Xavier shiningxc at gmail.com
Thu Mar 27 07:13:39 EDT 2008


Signed-off-by: Chantry Xavier <shiningxc at gmail.com>
---

Well, I saw that comment, so I gave it a try, but I am not sure if I did it
correctly. It doesn't seem too bad but maybe there are still cleaner ways.
Also I wasn't sure which buf size to choose, and how to comment the code.

Xav

 lib/libalpm/util.c |   30 ++++++++++++++++++++++++------
 1 files changed, 24 insertions(+), 6 deletions(-)

diff --git a/lib/libalpm/util.c b/lib/libalpm/util.c
index 92a0a26..0b7750e 100644
--- a/lib/libalpm/util.c
+++ b/lib/libalpm/util.c
@@ -675,22 +675,40 @@ int _alpm_test_md5sum(const char *filepath, const char *md5sum)
 
 char *_alpm_archive_fgets(char *line, size_t size, struct archive *a)
 {
-	/* for now, just read one char at a time until we get to a
-	 * '\n' char. we can optimize this later with an internal
-	 * buffer. */
+	/* internal buffer */
+	static char buf[BUFSIZ];
+	/* index of the next char to read in the buffer */
+	static int index = 0;
+	/* total number of char in the buffer */
+	static int nread = 0;
 	/* leave room for zero terminator */
 	int want = size - 1;
 	int loop;
 
 	for(loop = 0; loop < want; loop++) {
-		int ret = archive_read_data(a, line + loop, 1);
+		if(index == 0) {
+			/* fill the buffer */
+			nread = archive_read_data(a, buf, BUFSIZ);
+		}
+		if(index < nread) {
+			/* get the next char from the buffer */
+			line[loop] = buf[index++];
+		} else {
+			/* nothing left to read */
+			line[loop] = '\0';
+			index = 0;
+		}
+		if(index == BUFSIZ) {
+			/* end of the buffer, so reset the index to refill it */
+			index = 0;
+		}
 		/* special check for first read- if null, return null,
 		 * this indicates EOF */
-		if(loop == 0 && (ret <= 0 || line[loop] == '\0')) {
+		if(loop == 0 && line[loop] == '\0') {
 			return(NULL);
 		}
 		/* check if read value was null or newline */
-		if(ret <= 0 || line[loop] == '\0' || line[loop] == '\n') {
+		if(line[loop] == '\0' || line[loop] == '\n') {
 			want = loop + 1;
 			break;
 		}
-- 
1.5.4.4





More information about the pacman-dev mailing list