code: plan9front

Download patch

ref: 0ec0154bc9da3c0b48f2f2cae08347129a8ec3d4
parent: 23620b2e70e9de0ce31c6f4f21926a044c5deabc
author: Jacob Moody <moody@posixcafe.org>
date: Sun Jul 17 13:51:11 EDT 2022

ktrans: don't leak on conflicting jisho lines

Tidy up the hash interface to make cleanup
a bit more explicit vs non cleanup.

--- a/sys/src/cmd/ktrans/hash.c
+++ b/sys/src/cmd/ktrans/hash.c
@@ -47,7 +47,7 @@
 }
 
 int
-hmapset(Hmap **store, char *key, void *new, void *old)
+hmaprepl(Hmap **store, char *key, void *new, void *old, int freekeys)
 {
 	Hnode *n;
 	uchar *v;
@@ -66,6 +66,8 @@
 		if(n->filled == 0)
 			goto replace;
 		if(strcmp(n->key, key) == 0){
+			if(freekeys)
+				free(n->key);
 			oldv = v + Tagsize;
 			goto replace;
 		}
@@ -105,6 +107,18 @@
 	return 0;
 }
 
+int
+hmapupd(Hmap **h, char *key, void *new)
+{
+	char *prev;
+
+	prev = hmapkey(*h, key);
+	if(prev == nil)
+		prev = key;
+
+	return hmaprepl(h, prev, new, nil, 0);
+}
+
 void*
 _hmapget(Hmap *h, char *key)
 {
@@ -184,7 +198,7 @@
 	for(i=0 ; i < old->len; i++){
 		v = old->nodes + i*old->nsz;
 		n = (Hnode*)v;
-		hmapset(&new, n->key, v + Tagsize, nil);
+		hmaprepl(&new, n->key, v + Tagsize, nil, 0);
 	}
 	free(old);
 	return new;
--- a/sys/src/cmd/ktrans/hash.h
+++ b/sys/src/cmd/ktrans/hash.h
@@ -16,8 +16,8 @@
 
 Hmap*	hmapalloc(int nbuckets, int size);
 int	hmapget(Hmap *h, char *key, void *dst);
-int	hmapset(Hmap **h, char *key, void *new, void *old);
+int	hmaprepl(Hmap **h, char *key, void *new, void *old, int freekeys);
+int	hmapupd(Hmap **h, char *key, void *new);
 int	hmapdel(Hmap *h, char *key, void *dst, int freekey);
-void	hmapfree(Hmap *h, int freekeys);
 char*	hmapkey(Hmap *h, char *key);
 void	hmapreset(Hmap *h, int freekeys);
--- a/sys/src/cmd/ktrans/main.c
+++ b/sys/src/cmd/ktrans/main.c
@@ -122,14 +122,13 @@
 					//confict; partial & valid input
 					prev = m[i];
 					prev.leadstomore = 1;
-					free(hmapkey(h, buf));
 				}
 			}
 
 			if(s[1] == '\0'){
-				hmapset(&h, strdup(buf), &prev, nil);
+				hmaprepl(&h, strdup(buf), &prev, nil, 1);
 			} else {
-				hmapset(&h, strdup(buf), &signalmore, nil);
+				hmaprepl(&h, strdup(buf), &signalmore, nil, 1);
 			}
 			j++;
 		}
@@ -425,7 +424,7 @@
 			kouho[i] = rest;
 
 		/* key is the base pointer; overwrites clean up for us */
-		hmapset(&h, p, kouho, nil);
+		hmaprepl(&h, p, kouho, nil, 1);
 	}
 	Bterm(b);
 	return h;
@@ -537,7 +536,7 @@
 				p = kouho[0];
 				kouho[0] = kouho[i];
 				kouho[i] = p;
-				hmapset(&dic, hmapkey(dic, v), kouho, nil);
+				hmapupd(&dic, v, kouho);
 			}
 
 			olen = okuri = joshi = 0;