libvdb 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
libvdb-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Abdi Moalim
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
libvdb-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: libvdb
3
+ Version: 0.1.0
4
+ Summary: A header-only C vector database library
5
+ Requires-Python: >=3.13
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Dynamic: license-file
9
+
10
+ ### vdb
11
+
12
+ A lightweight, header-only C library for storing and searching high-dimensional vector embeddings with optional multithreading support.
13
+
14
+ ![](/benchmark.png)
15
+
16
+ ### Features
17
+
18
+ - Header-only implementation (single file: `vdb.h`)
19
+ - Multiple distance metrics (cosine, euclidean, dot product)
20
+ - Optional thread-safe operations via `#define VDB_MULTITHREADED`
21
+ - Save/load database to/from disk
22
+ - Custom memory allocators support
23
+ - No dependencies (except `pthreads` for multithreading)
24
+ - Python bindings (refer to [`vdb.py`](/vdb.py))
25
+
26
+ ### Usage
27
+
28
+ ```c
29
+ /*test.c*/
30
+ #include "vdb.h"
31
+
32
+ int main(void) {
33
+ vdb_database *db = vdb_create(128, VDB_METRIC_COSINE);
34
+
35
+ float embedding[128] = { /* ... */ };
36
+ vdb_add_vector(db, embedding, "vec1", NULL);
37
+
38
+ float query[128] = { /* ... */ };
39
+ vdb_result_set *results = vdb_search(db, query, 5);
40
+
41
+ vdb_free_result_set(results);
42
+ vdb_destroy(db);
43
+ return 0;
44
+ }
45
+ ```
46
+
47
+ Include [`vdb.h`](/vdb.h) and compile with either approach, `pthreads` is not necessarily available which is why this is behind a flag.
48
+
49
+ **Single-threaded:**
50
+
51
+ ```bash
52
+ gcc -O2 test.c -o test -lm
53
+ ```
54
+
55
+ **Multi-threaded:**
56
+
57
+ ```bash
58
+ gcc -O2 -DVDB_MULTITHREADED test.c -o test -lpthread -lm
59
+ ```
60
+
61
+ ### API Reference
62
+
63
+ #### Database management
64
+
65
+ **`vdb_database *vdb_create(size_t dimensions, vdb_metric metric)`**
66
+ Creates a new vector database.
67
+
68
+ **`void vdb_destroy(vdb_database *db)`**
69
+ Frees all resources associated with the database.
70
+
71
+ **`size_t vdb_count(const vdb_database *db)`**
72
+ Returns the number of vectors in the database.
73
+
74
+ **`size_t vdb_dimensions(const vdb_database *db)`**
75
+ Returns the dimensionality of vectors.
76
+
77
+ #### Vector operations
78
+
79
+ **`vdb_error vdb_add_vector(vdb_database *db, const float *data, const char *id, void *metadata)`**
80
+ Adds a vector to the database with optional ID and metadata.
81
+
82
+ **`vdb_error vdb_remove_vector(vdb_database *db, size_t index)`**
83
+ Removes a vector at the specified index.
84
+
85
+ **`vdb_error vdb_get_vector(const vdb_database \*db, size_t index, float **out_data, char **out_id, void **out_metadata)`\*\*
86
+ Retrieves a vector and its metadata.
87
+
88
+ #### Search
89
+
90
+ **`vdb_result_set *vdb_search(const vdb_database *db, const float *query, size_t k)`**
91
+ Performs [k-nearest neighbor](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) search. Returns NULL on error.
92
+
93
+ **`void vdb_free_result_set(vdb_result_set *result_set)`**
94
+ Frees search results.
95
+
96
+ #### Persistence
97
+
98
+ **`vdb_error vdb_save(const vdb_database *db, const char *filename)`**
99
+ Saves the database to disk.
100
+
101
+ **`vdb_database *vdb_load(const char *filename)`**
102
+ Loads a database from disk.
103
+
104
+ ### Distance metrics
105
+
106
+ - `VDB_METRIC_COSINE` - Cosine distance (1 - cosine similarity)
107
+ - `VDB_METRIC_EUCLIDEAN` - Euclidean (L2) distance
108
+ - `VDB_METRIC_DOT_PRODUCT` - Negative dot product
109
+
110
+ ### Error codes
111
+
112
+ ```c
113
+ VDB_OK = 0
114
+ VDB_ERROR_NULL_POINTER = -1
115
+ VDB_ERROR_INVALID_DIMENSIONS = -2
116
+ VDB_ERROR_OUT_OF_MEMORY = -3
117
+ VDB_ERROR_NOT_FOUND = -4
118
+ VDB_ERROR_INVALID_INDEX = -5
119
+ VDB_ERROR_THREAD_FAILURE = -6
120
+ ```
121
+
122
+ ### Custom memory allocators
123
+
124
+ Define before including `vdb.h`:
125
+
126
+ ```c
127
+ #define VDB_MALLOC my_malloc
128
+ #define VDB_FREE my_free
129
+ #define VDB_REALLOC my_realloc
130
+ #include "vdb.h"
131
+ ```
132
+
133
+ ### Thread safety
134
+
135
+ When compiled with `VDB_MULTITHREADED`, all operations are thread-safe using read-write locks:
136
+
137
+ - Multiple threads can search simultaneously
138
+ - Add/remove operations are exclusive
139
+ - No external locking required
140
+
141
+ ### File format
142
+
143
+ vdb uses a binary format with magic number `0x56444230`:
144
+
145
+ - Header: magic (4 bytes), dimensions, count, metric
146
+ - Vectors: float array + ID length + ID string (for each vector)
147
+ - Metadata is not persisted
148
+
149
+ ### License
150
+
151
+ Apache v2.0 License
libvdb-0.1.0/README.md ADDED
@@ -0,0 +1,142 @@
1
+ ### vdb
2
+
3
+ A lightweight, header-only C library for storing and searching high-dimensional vector embeddings with optional multithreading support.
4
+
5
+ ![](/benchmark.png)
6
+
7
+ ### Features
8
+
9
+ - Header-only implementation (single file: `vdb.h`)
10
+ - Multiple distance metrics (cosine, euclidean, dot product)
11
+ - Optional thread-safe operations via `#define VDB_MULTITHREADED`
12
+ - Save/load database to/from disk
13
+ - Custom memory allocators support
14
+ - No dependencies (except `pthreads` for multithreading)
15
+ - Python bindings (refer to [`vdb.py`](/vdb.py))
16
+
17
+ ### Usage
18
+
19
+ ```c
20
+ /*test.c*/
21
+ #include "vdb.h"
22
+
23
+ int main(void) {
24
+ vdb_database *db = vdb_create(128, VDB_METRIC_COSINE);
25
+
26
+ float embedding[128] = { /* ... */ };
27
+ vdb_add_vector(db, embedding, "vec1", NULL);
28
+
29
+ float query[128] = { /* ... */ };
30
+ vdb_result_set *results = vdb_search(db, query, 5);
31
+
32
+ vdb_free_result_set(results);
33
+ vdb_destroy(db);
34
+ return 0;
35
+ }
36
+ ```
37
+
38
+ Include [`vdb.h`](/vdb.h) and compile with either approach, `pthreads` is not necessarily available which is why this is behind a flag.
39
+
40
+ **Single-threaded:**
41
+
42
+ ```bash
43
+ gcc -O2 test.c -o test -lm
44
+ ```
45
+
46
+ **Multi-threaded:**
47
+
48
+ ```bash
49
+ gcc -O2 -DVDB_MULTITHREADED test.c -o test -lpthread -lm
50
+ ```
51
+
52
+ ### API Reference
53
+
54
+ #### Database management
55
+
56
+ **`vdb_database *vdb_create(size_t dimensions, vdb_metric metric)`**
57
+ Creates a new vector database.
58
+
59
+ **`void vdb_destroy(vdb_database *db)`**
60
+ Frees all resources associated with the database.
61
+
62
+ **`size_t vdb_count(const vdb_database *db)`**
63
+ Returns the number of vectors in the database.
64
+
65
+ **`size_t vdb_dimensions(const vdb_database *db)`**
66
+ Returns the dimensionality of vectors.
67
+
68
+ #### Vector operations
69
+
70
+ **`vdb_error vdb_add_vector(vdb_database *db, const float *data, const char *id, void *metadata)`**
71
+ Adds a vector to the database with optional ID and metadata.
72
+
73
+ **`vdb_error vdb_remove_vector(vdb_database *db, size_t index)`**
74
+ Removes a vector at the specified index.
75
+
76
+ **`vdb_error vdb_get_vector(const vdb_database \*db, size_t index, float **out_data, char **out_id, void **out_metadata)`\*\*
77
+ Retrieves a vector and its metadata.
78
+
79
+ #### Search
80
+
81
+ **`vdb_result_set *vdb_search(const vdb_database *db, const float *query, size_t k)`**
82
+ Performs [k-nearest neighbor](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) search. Returns NULL on error.
83
+
84
+ **`void vdb_free_result_set(vdb_result_set *result_set)`**
85
+ Frees search results.
86
+
87
+ #### Persistence
88
+
89
+ **`vdb_error vdb_save(const vdb_database *db, const char *filename)`**
90
+ Saves the database to disk.
91
+
92
+ **`vdb_database *vdb_load(const char *filename)`**
93
+ Loads a database from disk.
94
+
95
+ ### Distance metrics
96
+
97
+ - `VDB_METRIC_COSINE` - Cosine distance (1 - cosine similarity)
98
+ - `VDB_METRIC_EUCLIDEAN` - Euclidean (L2) distance
99
+ - `VDB_METRIC_DOT_PRODUCT` - Negative dot product
100
+
101
+ ### Error codes
102
+
103
+ ```c
104
+ VDB_OK = 0
105
+ VDB_ERROR_NULL_POINTER = -1
106
+ VDB_ERROR_INVALID_DIMENSIONS = -2
107
+ VDB_ERROR_OUT_OF_MEMORY = -3
108
+ VDB_ERROR_NOT_FOUND = -4
109
+ VDB_ERROR_INVALID_INDEX = -5
110
+ VDB_ERROR_THREAD_FAILURE = -6
111
+ ```
112
+
113
+ ### Custom memory allocators
114
+
115
+ Define before including `vdb.h`:
116
+
117
+ ```c
118
+ #define VDB_MALLOC my_malloc
119
+ #define VDB_FREE my_free
120
+ #define VDB_REALLOC my_realloc
121
+ #include "vdb.h"
122
+ ```
123
+
124
+ ### Thread safety
125
+
126
+ When compiled with `VDB_MULTITHREADED`, all operations are thread-safe using read-write locks:
127
+
128
+ - Multiple threads can search simultaneously
129
+ - Add/remove operations are exclusive
130
+ - No external locking required
131
+
132
+ ### File format
133
+
134
+ vdb uses a binary format with magic number `0x56444230`:
135
+
136
+ - Header: magic (4 bytes), dimensions, count, metric
137
+ - Vectors: float array + ID length + ID string (for each vector)
138
+ - Metadata is not persisted
139
+
140
+ ### License
141
+
142
+ Apache v2.0 License
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: libvdb
3
+ Version: 0.1.0
4
+ Summary: A header-only C vector database library
5
+ Requires-Python: >=3.13
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Dynamic: license-file
9
+
10
+ ### vdb
11
+
12
+ A lightweight, header-only C library for storing and searching high-dimensional vector embeddings with optional multithreading support.
13
+
14
+ ![](/benchmark.png)
15
+
16
+ ### Features
17
+
18
+ - Header-only implementation (single file: `vdb.h`)
19
+ - Multiple distance metrics (cosine, euclidean, dot product)
20
+ - Optional thread-safe operations via `#define VDB_MULTITHREADED`
21
+ - Save/load database to/from disk
22
+ - Custom memory allocators support
23
+ - No dependencies (except `pthreads` for multithreading)
24
+ - Python bindings (refer to [`vdb.py`](/vdb.py))
25
+
26
+ ### Usage
27
+
28
+ ```c
29
+ /*test.c*/
30
+ #include "vdb.h"
31
+
32
+ int main(void) {
33
+ vdb_database *db = vdb_create(128, VDB_METRIC_COSINE);
34
+
35
+ float embedding[128] = { /* ... */ };
36
+ vdb_add_vector(db, embedding, "vec1", NULL);
37
+
38
+ float query[128] = { /* ... */ };
39
+ vdb_result_set *results = vdb_search(db, query, 5);
40
+
41
+ vdb_free_result_set(results);
42
+ vdb_destroy(db);
43
+ return 0;
44
+ }
45
+ ```
46
+
47
+ Include [`vdb.h`](/vdb.h) and compile with either approach, `pthreads` is not necessarily available which is why this is behind a flag.
48
+
49
+ **Single-threaded:**
50
+
51
+ ```bash
52
+ gcc -O2 test.c -o test -lm
53
+ ```
54
+
55
+ **Multi-threaded:**
56
+
57
+ ```bash
58
+ gcc -O2 -DVDB_MULTITHREADED test.c -o test -lpthread -lm
59
+ ```
60
+
61
+ ### API Reference
62
+
63
+ #### Database management
64
+
65
+ **`vdb_database *vdb_create(size_t dimensions, vdb_metric metric)`**
66
+ Creates a new vector database.
67
+
68
+ **`void vdb_destroy(vdb_database *db)`**
69
+ Frees all resources associated with the database.
70
+
71
+ **`size_t vdb_count(const vdb_database *db)`**
72
+ Returns the number of vectors in the database.
73
+
74
+ **`size_t vdb_dimensions(const vdb_database *db)`**
75
+ Returns the dimensionality of vectors.
76
+
77
+ #### Vector operations
78
+
79
+ **`vdb_error vdb_add_vector(vdb_database *db, const float *data, const char *id, void *metadata)`**
80
+ Adds a vector to the database with optional ID and metadata.
81
+
82
+ **`vdb_error vdb_remove_vector(vdb_database *db, size_t index)`**
83
+ Removes a vector at the specified index.
84
+
85
+ **`vdb_error vdb_get_vector(const vdb_database \*db, size_t index, float **out_data, char **out_id, void **out_metadata)`\*\*
86
+ Retrieves a vector and its metadata.
87
+
88
+ #### Search
89
+
90
+ **`vdb_result_set *vdb_search(const vdb_database *db, const float *query, size_t k)`**
91
+ Performs [k-nearest neighbor](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) search. Returns NULL on error.
92
+
93
+ **`void vdb_free_result_set(vdb_result_set *result_set)`**
94
+ Frees search results.
95
+
96
+ #### Persistence
97
+
98
+ **`vdb_error vdb_save(const vdb_database *db, const char *filename)`**
99
+ Saves the database to disk.
100
+
101
+ **`vdb_database *vdb_load(const char *filename)`**
102
+ Loads a database from disk.
103
+
104
+ ### Distance metrics
105
+
106
+ - `VDB_METRIC_COSINE` - Cosine distance (1 - cosine similarity)
107
+ - `VDB_METRIC_EUCLIDEAN` - Euclidean (L2) distance
108
+ - `VDB_METRIC_DOT_PRODUCT` - Negative dot product
109
+
110
+ ### Error codes
111
+
112
+ ```c
113
+ VDB_OK = 0
114
+ VDB_ERROR_NULL_POINTER = -1
115
+ VDB_ERROR_INVALID_DIMENSIONS = -2
116
+ VDB_ERROR_OUT_OF_MEMORY = -3
117
+ VDB_ERROR_NOT_FOUND = -4
118
+ VDB_ERROR_INVALID_INDEX = -5
119
+ VDB_ERROR_THREAD_FAILURE = -6
120
+ ```
121
+
122
+ ### Custom memory allocators
123
+
124
+ Define before including `vdb.h`:
125
+
126
+ ```c
127
+ #define VDB_MALLOC my_malloc
128
+ #define VDB_FREE my_free
129
+ #define VDB_REALLOC my_realloc
130
+ #include "vdb.h"
131
+ ```
132
+
133
+ ### Thread safety
134
+
135
+ When compiled with `VDB_MULTITHREADED`, all operations are thread-safe using read-write locks:
136
+
137
+ - Multiple threads can search simultaneously
138
+ - Add/remove operations are exclusive
139
+ - No external locking required
140
+
141
+ ### File format
142
+
143
+ vdb uses a binary format with magic number `0x56444230`:
144
+
145
+ - Header: magic (4 bytes), dimensions, count, metric
146
+ - Vectors: float array + ID length + ID string (for each vector)
147
+ - Metadata is not persisted
148
+
149
+ ### License
150
+
151
+ Apache v2.0 License
@@ -0,0 +1,8 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ vdb.py
5
+ libvdb.egg-info/PKG-INFO
6
+ libvdb.egg-info/SOURCES.txt
7
+ libvdb.egg-info/dependency_links.txt
8
+ libvdb.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ vdb
@@ -0,0 +1,14 @@
1
+ [project]
2
+ name = "libvdb"
3
+ version = "0.1.0"
4
+ description = "A header-only C vector database library"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = []
8
+
9
+ [build-system]
10
+ requires = ["setuptools"]
11
+ build-backend = "setuptools.build_meta"
12
+
13
+ [tool.setuptools]
14
+ py-modules = ["vdb"]
libvdb-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
libvdb-0.1.0/vdb.py ADDED
@@ -0,0 +1,225 @@
1
+ import ctypes
2
+ import os
3
+ import tempfile
4
+ import subprocess
5
+ from ctypes import c_void_p, c_char_p, c_size_t, c_float, c_int, POINTER, Structure
6
+
7
+ class VDBError:
8
+ OK = 0
9
+ NULL_POINTER = -1
10
+ INVALID_DIMENSIONS = -2
11
+ OUT_OF_MEMORY = -3
12
+ NOT_FOUND = -4
13
+ INVALID_INDEX = -5
14
+ THREAD_FAILURE = -6
15
+
16
+ class VDBMetric:
17
+ COSINE = 0
18
+ EUCLIDEAN = 1
19
+ DOT_PRODUCT = 2
20
+
21
+ class VDBResult(Structure):
22
+ _fields_ = [
23
+ ("index", c_size_t),
24
+ ("distance", c_float),
25
+ ("id", c_char_p),
26
+ ("metadata", c_void_p)
27
+ ]
28
+
29
+ class VDBResultSet(Structure):
30
+ _fields_ = [
31
+ ("results", POINTER(VDBResult)),
32
+ ("count", c_size_t)
33
+ ]
34
+
35
+ class VectorDatabase:
36
+ _lib = None
37
+ _lib_path = None
38
+
39
+ @classmethod
40
+ def _compile_library(cls, multithreaded=True):
41
+ if cls._lib is not None:
42
+ return
43
+
44
+ vdb_header = os.path.join(os.path.dirname(__file__), 'vdb.h')
45
+ if not os.path.exists(vdb_header):
46
+ vdb_header = 'vdb.h'
47
+
48
+ temp_dir = tempfile.gettempdir()
49
+ c_file = os.path.join(temp_dir, 'vdb_wrapper.c')
50
+
51
+ wrapper_code = '''
52
+ #define VDB_MULTITHREADED
53
+ #include "vdb.h"
54
+
55
+ vdb_database* wrap_vdb_create(size_t dims, int metric) {
56
+ return vdb_create(dims, (vdb_metric)metric);
57
+ }
58
+
59
+ int wrap_vdb_add_vector(vdb_database* db, float* data, const char* id) {
60
+ return vdb_add_vector(db, data, id, NULL);
61
+ }
62
+
63
+ vdb_result_set* wrap_vdb_search(vdb_database* db, float* query, size_t k) {
64
+ return vdb_search(db, query, k);
65
+ }
66
+
67
+ void wrap_vdb_free_result_set(vdb_result_set* rs) {
68
+ vdb_free_result_set(rs);
69
+ }
70
+
71
+ void wrap_vdb_destroy(vdb_database* db) {
72
+ vdb_destroy(db);
73
+ }
74
+
75
+ size_t wrap_vdb_count(vdb_database* db) {
76
+ return vdb_count(db);
77
+ }
78
+
79
+ size_t wrap_vdb_dimensions(vdb_database* db) {
80
+ return vdb_dimensions(db);
81
+ }
82
+
83
+ int wrap_vdb_save(vdb_database* db, const char* filename) {
84
+ return vdb_save(db, filename);
85
+ }
86
+
87
+ vdb_database* wrap_vdb_load(const char* filename) {
88
+ return vdb_load(filename);
89
+ }
90
+
91
+ int wrap_vdb_remove_vector(vdb_database* db, size_t index) {
92
+ return vdb_remove_vector(db, index);
93
+ }
94
+ '''
95
+
96
+ with open(c_file, 'w') as f:
97
+ f.write(wrapper_code)
98
+
99
+ lib_name = 'libvdb.so'
100
+ lib_path = os.path.join(temp_dir, lib_name)
101
+
102
+ compile_cmd = [
103
+ 'gcc', '-shared', '-fPIC', '-O3',
104
+ '-I' + os.path.dirname(vdb_header),
105
+ c_file, '-o', lib_path,
106
+ '-lm', '-lpthread'
107
+ ]
108
+
109
+ result = subprocess.run(compile_cmd, capture_output=True, text=True)
110
+ if result.returncode != 0:
111
+ raise RuntimeError(f"Compilation failed: {result.stderr}")
112
+
113
+ cls._lib_path = lib_path
114
+ cls._lib = ctypes.CDLL(lib_path)
115
+
116
+ cls._lib.wrap_vdb_create.argtypes = [c_size_t, c_int]
117
+ cls._lib.wrap_vdb_create.restype = c_void_p
118
+
119
+ cls._lib.wrap_vdb_add_vector.argtypes = [c_void_p, POINTER(c_float), c_char_p]
120
+ cls._lib.wrap_vdb_add_vector.restype = c_int
121
+
122
+ cls._lib.wrap_vdb_search.argtypes = [c_void_p, POINTER(c_float), c_size_t]
123
+ cls._lib.wrap_vdb_search.restype = POINTER(VDBResultSet)
124
+
125
+ cls._lib.wrap_vdb_free_result_set.argtypes = [POINTER(VDBResultSet)]
126
+ cls._lib.wrap_vdb_free_result_set.restype = None
127
+
128
+ cls._lib.wrap_vdb_destroy.argtypes = [c_void_p]
129
+ cls._lib.wrap_vdb_destroy.restype = None
130
+
131
+ cls._lib.wrap_vdb_count.argtypes = [c_void_p]
132
+ cls._lib.wrap_vdb_count.restype = c_size_t
133
+
134
+ cls._lib.wrap_vdb_dimensions.argtypes = [c_void_p]
135
+ cls._lib.wrap_vdb_dimensions.restype = c_size_t
136
+
137
+ cls._lib.wrap_vdb_save.argtypes = [c_void_p, c_char_p]
138
+ cls._lib.wrap_vdb_save.restype = c_int
139
+
140
+ cls._lib.wrap_vdb_load.argtypes = [c_char_p]
141
+ cls._lib.wrap_vdb_load.restype = c_void_p
142
+
143
+ cls._lib.wrap_vdb_remove_vector.argtypes = [c_void_p, c_size_t]
144
+ cls._lib.wrap_vdb_remove_vector.restype = c_int
145
+
146
+ def __init__(self, dimensions, metric=VDBMetric.COSINE, multithreaded=True):
147
+ VectorDatabase._compile_library(multithreaded)
148
+ self.db = self._lib.wrap_vdb_create(dimensions, metric)
149
+ if not self.db:
150
+ raise RuntimeError("Failed to create database")
151
+ self.dimensions = dimensions
152
+ self.metric = metric
153
+
154
+ def add_vector(self, vector, vector_id=None):
155
+ if len(vector) != self.dimensions:
156
+ raise ValueError(f"Vector dimension mismatch: expected {self.dimensions}, got {len(vector)}")
157
+
158
+ arr = (c_float * len(vector))(*vector)
159
+ id_bytes = vector_id.encode('utf-8') if vector_id else None
160
+
161
+ result = self._lib.wrap_vdb_add_vector(self.db, arr, id_bytes)
162
+ if result != VDBError.OK:
163
+ raise RuntimeError(f"Failed to add vector: error {result}")
164
+
165
+ def search(self, query, k=5):
166
+ if len(query) != self.dimensions:
167
+ raise ValueError(f"Query dimension mismatch: expected {self.dimensions}, got {len(query)}")
168
+
169
+ arr = (c_float * len(query))(*query)
170
+ result_set_ptr = self._lib.wrap_vdb_search(self.db, arr, k)
171
+
172
+ if not result_set_ptr:
173
+ return []
174
+
175
+ result_set = result_set_ptr.contents
176
+ results = []
177
+
178
+ for i in range(result_set.count):
179
+ res = result_set.results[i]
180
+ results.append({
181
+ 'index': res.index,
182
+ 'distance': res.distance,
183
+ 'id': res.id.decode('utf-8') if res.id else None
184
+ })
185
+
186
+ self._lib.wrap_vdb_free_result_set(result_set_ptr)
187
+ return results
188
+
189
+ def remove_vector(self, index):
190
+ result = self._lib.wrap_vdb_remove_vector(self.db, index)
191
+ if result != VDBError.OK:
192
+ raise RuntimeError(f"Failed to remove vector: error {result}")
193
+
194
+ def count(self):
195
+ return self._lib.wrap_vdb_count(self.db)
196
+
197
+ def save(self, filename):
198
+ result = self._lib.wrap_vdb_save(self.db, filename.encode('utf-8'))
199
+ if result != VDBError.OK:
200
+ raise RuntimeError(f"Failed to save database: error {result}")
201
+
202
+ @classmethod
203
+ def load(cls, filename):
204
+ cls._compile_library()
205
+ db_ptr = cls._lib.wrap_vdb_load(filename.encode('utf-8'))
206
+ if not db_ptr:
207
+ raise RuntimeError("Failed to load database")
208
+
209
+ instance = cls.__new__(cls)
210
+ instance.db = db_ptr
211
+ instance.dimensions = cls._lib.wrap_vdb_dimensions(db_ptr)
212
+ instance.metric = VDBMetric.COSINE
213
+ return instance
214
+
215
+ def __del__(self):
216
+ if hasattr(self, 'db') and self.db:
217
+ self._lib.wrap_vdb_destroy(self.db)
218
+
219
+ def __enter__(self):
220
+ return self
221
+
222
+ def __exit__(self, exc_type, exc_val, exc_tb):
223
+ if self.db:
224
+ self._lib.wrap_vdb_destroy(self.db)
225
+ self.db = None