shithub: asif

Download patch

ref: 7db5c89b79e75bebc3b9bc9fdb2e9cdf691bedb7
parent: f5168ddecc361ecc1bc4058cba43593a743b18bb
author: qwx <[email protected]>
date: Tue Sep 13 22:10:33 EDT 2022

hash/knr: fix value traversal and add long integer only functions

--- a/asif.h
+++ b/asif.h
@@ -77,8 +77,12 @@
 	HPair b[Hashsz];
 };
 
+int	htremovel(HTab*, u32int);
+void*	htgetl(HTab*, u32int);
+int	htputl(HTab*, u32int, void*);
+int	htremove(HTab*, char*);
 void*	htget(HTab*, char*);
-void	htput(HTab*, char*, void*);
+int	htput(HTab*, char*, void*);
 HTab*	htalloc(void);
 
 typedef struct Pairheap Pairheap;
--- a/hash/knr.c
+++ b/hash/knr.c
@@ -15,35 +15,97 @@
 	return h % Hashsz;
 }
 
-void *
-htget(HTab *ht, char *key)
+static HPair *
+find(HTab *ht, char *key, HPair **prev)
 {
-	HPair *k;
+	HPair *k, *kp;
 
 	if(ht == nil)
 		return nil;
-	for(k=ht->b[hash(key)].next; k!=nil; k=k->next)
+	kp = &ht->b[hash(key)];
+	if(prev != nil)
+		*prev = kp;
+	for(k=kp->next; k!=nil; kp=k, k=k->next){
+		if(prev != nil)
+			*prev = kp;
 		if(strcmp(key, k->key) == 0)
-			return k->val;
+			return k;
+	}
 	return nil;
 }
 
-void
+static char *
+bytestr(u32int key)
+{
+	static char u[5];
+
+	u[0] = key;
+	u[1] = key >> 8;
+	u[2] = key >> 16;
+	u[3] = key >> 24;
+	u[4] = 0;
+	return u;
+}
+
+int
+htremove(HTab *ht, char *key)
+{
+	HPair *k, *kp;
+
+	if((k = find(ht, key, &kp)) == nil){
+		werrstr("no such key \"%s\"", key);
+		return -1;
+	}
+	kp->next = k->next;
+	free(k->key);
+	free(k);
+	return 0;
+}
+
+int
+htremovel(HTab *ht, u32int key)
+{
+	return htremove(ht, bytestr(key));
+}
+
+void *
+htget(HTab *ht, char *key)
+{
+	HPair *k;
+
+	if((k = find(ht, key, nil)) == nil){
+		werrstr("no such key \"%s\"", key);
+		return nil;
+	}
+	return k->val;
+}
+
+void *
+htgetl(HTab *ht, u32int key)
+{
+	return htget(ht, bytestr(key));
+}
+
+int
 htput(HTab *ht, char *key, void *val)
 {
 	HPair *kp, *k;
 
-	if(ht == nil)
-		return;
-	for(kp=&ht->b[hash(key)], k=kp->next; k!=nil; kp=k, k=k->next)
-		if(strcmp(key, k->key) == 0){
-			k->val = val;
-			return;
-		}
+	if((k = find(ht, key, &kp)) != nil){
+		k->val = val;
+		return 0;
+	}
 	k = emalloc(sizeof *k);
 	k->key = estrdup(key);
 	k->val = val;
 	kp->next = k;
+	return 0;
+}
+
+int
+htputl(HTab *ht, u32int key, void *val)
+{
+	return htput(ht, bytestr(key), val);
 }
 
 HTab *