GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-b4e4cb0fe9
btree/update.c
Go to the documentation of this file.
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <grass/btree.h>
5 
6 static void *store(const void *, int);
7 
8 int btree_update(BTREE *B, const void *key, int keylen, const void *data,
9  int datalen)
10 {
11  int p = 0;
12  int q;
13  int N;
14  int (*cmp)(const void *, const void *);
15  int dir;
16 
17  /* first node is special case */
18  N = B->N;
19  if (N == 0) {
20  N = B->N = 1;
21  B->node[N].key = store(key, keylen);
22  B->node[N].data = store(data, datalen);
23  B->node[N].left = 0;
24  B->node[N].right = 0;
25  if (B->node[N].key && B->node[N].data)
26  return 1;
27  else
28  return 0;
29  }
30 
31  cmp = B->cmp;
32 
33  q = 1;
34  while (q > 0) {
35  p = q;
36  dir = (*cmp)(B->node[q].key, key);
37  if (dir == 0) {
38  free(B->node[q].data);
39  return ((B->node[q].data = store(data, datalen))) ? 1 : 0;
40  }
41  if (dir > 0)
42  q = B->node[q].left; /* go left */
43  else
44  q = B->node[q].right; /* go right */
45  }
46 
47  /* new node */
48  B->N++;
49  N = B->N;
50 
51  /* grow the tree? */
52  if (N >= B->tlen) {
53  B->node = (BTREE_NODE *)realloc(B->node, sizeof(BTREE_NODE) *
54  (B->tlen += B->incr));
55  if (B->node == NULL)
56  return 0;
57  }
58 
59  /* add node to tree */
60  B->node[N].key = store(key, keylen);
61  B->node[N].data = store(data, datalen);
62  B->node[N].left = 0;
63 
64  if (dir > 0) {
65  B->node[N].right = -p; /* create thread */
66  B->node[p].left = N; /* insert left */
67  }
68  else {
69  B->node[N].right = B->node[p].right; /* copy right link/thread */
70  B->node[p].right = N; /* add right */
71  }
72  return 1;
73 }
74 
75 static void *store(const void *s, int n)
76 {
77  void *b;
78 
79  if (n <= 0)
80  return NULL;
81 
82  b = malloc(n);
83  if (b == NULL)
84  return b;
85 
86  memcpy(b, s, n);
87 
88  return b;
89 }
int btree_update(BTREE *B, const void *key, int keylen, const void *data, int datalen)
Definition: btree/update.c:8
#define NULL
Definition: ccmath.h:32
#define N
Definition: e_intersect.c:926
double b
Definition: r_raster.c:39
void * malloc(YYSIZE_T)
void free(void *)
int left
Definition: btree.h:7
int right
Definition: btree.h:8
void * key
Definition: btree.h:5
void * data
Definition: btree.h:6
Definition: btree.h:11
int N
Definition: btree.h:14
int(* cmp)(const void *, const void *)
Definition: btree.h:17
int incr
Definition: btree.h:15
BTREE_NODE * node
Definition: btree.h:12
int tlen
Definition: btree.h:13