git/test-treap.c
Jason Evans 951f316470 Add treap implementation
Provide macros to generate a type-specific treap implementation and
various functions to operate on it. It uses obj_pool.h to store memory
nodes in a treap.  Previously committed nodes are never removed from
the pool; after any *_commit operation, it is assumed (correctly, in
the case of svn-fast-export) that someone else must care about them.

Treaps provide a memory-efficient binary search tree structure.
Insertion/deletion/search are about as about as fast in the average
case as red-black trees and the chances of worst-case behavior are
vanishingly small, thanks to (pseudo-)randomness.  The bad worst-case
behavior is a small price to pay, given that treaps are much simpler
to implement.

>From http://www.canonware.com/download/trp/trp_hash/trp.h

[db: Altered to reference nodes by offset from a common base pointer]
[db: Bob Jenkins' hashing implementation dropped for Knuth's]
[db: Methods unnecessary for search and insert dropped]
[rr: Squelched compiler warnings]
[db: Added support for immutable treap nodes]
[jn: Reintroduced treap_nsearch(); with tests]

Signed-off-by: David Barr <david.barr@cordelta.com>
Signed-off-by: Ramkumar Ramachandra <artagnon@gmail.com>
Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
2010-08-14 19:35:37 -07:00

66 lines
1.5 KiB
C

/*
* test-treap.c: code to exercise the svn importer's treap structure
*/
#include "cache.h"
#include "vcs-svn/obj_pool.h"
#include "vcs-svn/trp.h"
struct int_node {
uintmax_t n;
struct trp_node children;
};
obj_pool_gen(node, struct int_node, 3)
static int node_cmp(struct int_node *a, struct int_node *b)
{
return (a->n > b->n) - (a->n < b->n);
}
trp_gen(static, treap_, struct int_node, children, node, node_cmp)
static void strtonode(struct int_node *item, const char *s)
{
char *end;
item->n = strtoumax(s, &end, 10);
if (*s == '\0' || (*end != '\n' && *end != '\0'))
die("invalid integer: %s", s);
}
int main(int argc, char *argv[])
{
struct strbuf sb = STRBUF_INIT;
struct trp_root root = { ~0 };
uint32_t item;
if (argc != 1)
usage("test-treap < ints");
while (strbuf_getline(&sb, stdin, '\n') != EOF) {
item = node_alloc(1);
strtonode(node_pointer(item), sb.buf);
treap_insert(&root, node_pointer(item));
}
item = node_offset(treap_first(&root));
while (~item) {
uint32_t next;
struct int_node *tmp = node_pointer(node_alloc(1));
tmp->n = node_pointer(item)->n;
next = node_offset(treap_next(&root, node_pointer(item)));
treap_remove(&root, node_pointer(item));
item = node_offset(treap_nsearch(&root, tmp));
if (item != next && (!~item || node_pointer(item)->n != tmp->n))
die("found %"PRIuMAX" in place of %"PRIuMAX"",
~item ? node_pointer(item)->n : ~(uintmax_t) 0,
~next ? node_pointer(next)->n : ~(uintmax_t) 0);
printf("%"PRIuMAX"\n", tmp->n);
}
node_reset();
return 0;
}