[or-cvs] Add sorting/searching to smartlist

Nick Mathewson nickm at seul.org
Fri Sep 9 23:12:56 UTC 2005


Update of /home/or/cvsroot/tor/src/common
In directory moria:/tmp/cvs-serv31176/src/common

Modified Files:
	container.c container.h 
Log Message:
Add sorting/searching to smartlist

Index: container.c
===================================================================
RCS file: /home/or/cvsroot/tor/src/common/container.c,v
retrieving revision 1.33
retrieving revision 1.34
diff -u -d -r1.33 -r1.34
--- container.c	8 Sep 2005 06:47:27 -0000	1.33
+++ container.c	9 Sep 2005 23:12:54 -0000	1.34
@@ -387,6 +387,37 @@
   return r;
 }
 
+/** Sort the members of <b>sl</b> into an order defined by
+ * the ordering function <b>compare</b>, which returns less then 0 if a
+ * precedes b, greater than 0 if b precedes a, and 0 if a 'equals' b.
+ */
+void
+smartlist_sort(smartlist_t *sl, int (*compare)(const void **a, const void **b))
+{
+  if (!sl->num_used)
+    return;
+  qsort(sl->list, sl->num_used, sizeof(void*),
+        (int (*)(const void *,const void*))compare);
+}
+
+/** Assuming the members of <b>sl</b> are in order, return a pointer to the
+ * member which matches <b>key</b>.  Ordering and matching are defined by a
+ * <b>compare</b> function, which returns 0 on a match; less than 0 if key is
+ * less than member, and greater than 0 if key is greater then member.
+ */
+void *
+smartlist_bsearch(smartlist_t *sl, const void *key,
+                  int (*compare)(const void *key, const void **member))
+{
+  void ** r;
+  if (!sl->num_used)
+    return NULL;
+
+  r = bsearch(key, sl->list, sl->num_used, sizeof(void*),
+              (int (*)(const void *, const void *))compare);
+  return r ? *r : NULL;
+}
+
 /* Splay-tree implementation of string-to-void* map
  */
 typedef struct strmap_entry_t {

Index: container.h
===================================================================
RCS file: /home/or/cvsroot/tor/src/common/container.h,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -d -r1.14 -r1.15
--- container.h	22 Jul 2005 21:12:10 -0000	1.14
+++ container.h	9 Sep 2005 23:12:54 -0000	1.15
@@ -50,6 +50,10 @@
 void smartlist_del(smartlist_t *sl, int idx);
 void smartlist_del_keeporder(smartlist_t *sl, int idx);
 void smartlist_insert(smartlist_t *sl, int idx, void *val);
+void smartlist_sort(smartlist_t *sl,
+                    int (*compare)(const void **a, const void **b));
+void *smartlist_bsearch(smartlist_t *sl, const void *key,
+                        int (*compare)(const void *key, const void **member));
 
 #define SPLIT_SKIP_SPACE   0x01
 #define SPLIT_IGNORE_BLANK 0x02



More information about the tor-commits mailing list