GRASS GIS 8 Programmer's Manual
8.5.0dev(2024)-bea8435a9e
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
}
btree_update
int btree_update(BTREE *B, const void *key, int keylen, const void *data, int datalen)
Definition:
btree/update.c:8
btree.h
NULL
#define NULL
Definition:
ccmath.h:32
N
#define N
Definition:
e_intersect.c:926
b
double b
Definition:
r_raster.c:39
malloc
void * malloc(YYSIZE_T)
free
void free(void *)
BTREE_NODE
Definition:
btree.h:4
BTREE_NODE::left
int left
Definition:
btree.h:7
BTREE_NODE::right
int right
Definition:
btree.h:8
BTREE_NODE::key
void * key
Definition:
btree.h:5
BTREE_NODE::data
void * data
Definition:
btree.h:6
BTREE
Definition:
btree.h:11
BTREE::N
int N
Definition:
btree.h:14
BTREE::cmp
int(* cmp)(const void *, const void *)
Definition:
btree.h:17
BTREE::incr
int incr
Definition:
btree.h:15
BTREE::node
BTREE_NODE * node
Definition:
btree.h:12
BTREE::tlen
int tlen
Definition:
btree.h:13
lib
btree
update.c
Generated on Sun Nov 24 2024 07:03:41 for GRASS GIS 8 Programmer's Manual by
1.9.1