fcb_core 0.7.8

FlatCityBuf is a library for reading and writing CityJSON with FlatBuffers. Contains code derived from FlatGeobuf (BSD-2-Clause) for spatial indexing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::collections::HashMap;
use std::marker::PhantomData;

use crate::static_btree::error::{Error, Result};
use crate::static_btree::key::{Key, KeyType};
use crate::static_btree::query::types::{Operator, QueryCondition};
use crate::static_btree::stree::http::HttpSearchResultItem;
use crate::static_btree::stree::Stree;
use async_trait::async_trait;
use http_range_client::{AsyncBufferedHttpRangeClient, AsyncHttpRangeClient};

/// HTTP-based index for remote access
#[derive(Debug, Clone)]
pub struct HttpIndex<K: Key> {
    /// total number of items in the tree
    num_items: usize,
    /// branching factor of the B+tree
    branching_factor: u16,
    /// byte offset where the index begins
    index_begin: usize,
    /// byte offset where the feature data begins
    feature_begin: usize,
    /// threshold for combining HTTP requests to reduce roundtrips
    combine_request_threshold: usize,
    _marker: PhantomData<K>,
}

impl<K: Key> HttpIndex<K> {
    /// Create a new HTTP index descriptor with all necessary metadata
    pub fn new(
        num_items: usize,
        branching_factor: u16,
        index_begin: usize,
        feature_begin: usize,
        combine_request_threshold: usize,
    ) -> Self {
        Self {
            num_items,
            branching_factor,
            index_begin,
            feature_begin,
            combine_request_threshold,
            _marker: PhantomData,
        }
    }

    /// Find exact matches for a key via HTTP
    pub async fn find_exact<T: AsyncHttpRangeClient>(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        key: K,
    ) -> Result<Vec<HttpSearchResultItem>> {
        let items: Vec<HttpSearchResultItem> = Stree::http_stream_find_exact(
            client,
            self.index_begin,
            self.feature_begin,
            self.num_items,
            self.branching_factor,
            key.clone(),
            self.combine_request_threshold,
        )
        .await?;

        Ok(items)
    }

    /// Find all items in [start..end] via HTTP. At least one bound is required.
    pub async fn find_range<T: AsyncHttpRangeClient>(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        start: Option<K>,
        end: Option<K>,
    ) -> Result<Vec<HttpSearchResultItem>> {
        let (lower, upper) = match (start, end) {
            (Some(lo), Some(hi)) => (lo, hi),
            (Some(lo), None) => (lo, K::max_value()),
            (None, Some(hi)) => (K::min_value(), hi),
            (None, None) => {
                return Err(Error::QueryError(
                    "find_range requires at least one bound".to_string(),
                ));
            }
        };

        let items: Vec<HttpSearchResultItem> = Stree::http_stream_find_range(
            client,
            self.index_begin,
            self.feature_begin,
            self.num_items,
            self.branching_factor,
            lower.clone(),
            upper.clone(),
            self.combine_request_threshold,
        )
        .await?;

        Ok(items)
    }

    /// Find all items in the range via HTTP, with each bound independently
    /// strict (exclusive) or inclusive. A `None` bound is the type's min/max
    /// sentinel and is never strict.
    ///
    /// `Gt`/`Lt`/`Ne` lower to this instead of subtracting `find_exact` from
    /// an inclusive range: the subtraction removes feature offsets, and one
    /// feature can be indexed under several keys, so it deletes features that
    /// match through a different key.
    pub async fn find_range_strict<T: AsyncHttpRangeClient>(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        start: Option<K>,
        start_strict: bool,
        end: Option<K>,
        end_strict: bool,
    ) -> Result<Vec<HttpSearchResultItem>> {
        let lower = start.unwrap_or_else(K::min_value);
        let upper = end.unwrap_or_else(K::max_value);

        let items: Vec<HttpSearchResultItem> = Stree::http_stream_find_range_strict(
            client,
            self.index_begin,
            self.feature_begin,
            self.num_items,
            self.branching_factor,
            lower,
            start_strict,
            upper,
            end_strict,
            self.combine_request_threshold,
        )
        .await?;

        Ok(items)
    }
}

/// Trait for HTTP indices with heterogeneous key support
#[cfg(not(target_arch = "wasm32"))]
#[async_trait]
pub trait TypedHttpSearchIndex<T: AsyncHttpRangeClient + Send + Sync>:
    Send + Sync + std::fmt::Debug
{
    /// Execute a typed query condition over HTTP with a specific HTTP client
    async fn execute_query_condition(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        condition: &QueryCondition,
    ) -> Result<Vec<HttpSearchResultItem>>;
}

/// Wasm-specific version that doesn't require Send + Sync
#[cfg(target_arch = "wasm32")]
#[async_trait(?Send)]
pub trait TypedHttpSearchIndex<T: AsyncHttpRangeClient>: std::fmt::Debug {
    /// Execute a typed query condition over HTTP with a specific HTTP client
    async fn execute_query_condition(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        condition: &QueryCondition,
    ) -> Result<Vec<HttpSearchResultItem>>;
}

/// Implement the TypedHttpSearchIndex trait for each supported key type
macro_rules! impl_typed_http_search_index {
    ($key_type:ty, $enum_variant:path) => {
        #[cfg(not(target_arch = "wasm32"))]
        #[async_trait]
        impl<T: AsyncHttpRangeClient + Send + Sync> TypedHttpSearchIndex<T>
            for HttpIndex<$key_type>
        {
            async fn execute_query_condition(
                &self,
                client: &mut AsyncBufferedHttpRangeClient<T>,
                condition: &QueryCondition,
            ) -> Result<Vec<HttpSearchResultItem>> {
                // Extract the key value from the enum variant
                let key: $key_type = match &condition.key {
                    $enum_variant(val) => val.clone(),
                    _ => {
                        return Err(Error::QueryError(format!(
                            "key type mismatch: expected {}, got {:?}",
                            stringify!($key_type),
                            condition.key
                        )))
                    }
                };

                // Dispatch to exact or range methods
                let results = match condition.operator {
                    Operator::Eq => self.find_exact(client, key.clone()).await?,
                    // Two half-open scans rather than a full scan minus the
                    // equal set: subtraction on feature offsets is wrong when
                    // one feature carries several values of the attribute.
                    Operator::Ne => {
                        let mut below = self
                            .find_range_strict(client, None, false, Some(key.clone()), true)
                            .await?;
                        let above = self
                            .find_range_strict(client, Some(key.clone()), true, None, false)
                            .await?;
                        below.extend(above);
                        below
                    }
                    Operator::Gt => {
                        self.find_range_strict(client, Some(key.clone()), true, None, false)
                            .await?
                    }
                    Operator::Lt => {
                        self.find_range_strict(client, None, false, Some(key.clone()), true)
                            .await?
                    }
                    Operator::Ge => {
                        self.find_range_strict(client, Some(key.clone()), false, None, false)
                            .await?
                    }
                    Operator::Le => {
                        self.find_range_strict(client, None, false, Some(key.clone()), false)
                            .await?
                    }
                };
                Ok(results)
            }
        }

        #[cfg(target_arch = "wasm32")]
        #[async_trait(?Send)]
        impl<T: AsyncHttpRangeClient> TypedHttpSearchIndex<T> for HttpIndex<$key_type> {
            async fn execute_query_condition(
                &self,
                client: &mut AsyncBufferedHttpRangeClient<T>,
                condition: &QueryCondition,
            ) -> Result<Vec<HttpSearchResultItem>> {
                // Extract the key value from the enum variant
                let key: $key_type = match &condition.key {
                    $enum_variant(val) => val.clone(),
                    _ => {
                        return Err(Error::QueryError(format!(
                            "key type mismatch: expected {}, got {:?}",
                            stringify!($key_type),
                            condition.key
                        )))
                    }
                };

                // Dispatch to exact or range methods
                let results = match condition.operator {
                    Operator::Eq => self.find_exact(client, key.clone()).await?,
                    // Two half-open scans rather than a full scan minus the
                    // equal set: subtraction on feature offsets is wrong when
                    // one feature carries several values of the attribute.
                    Operator::Ne => {
                        let mut below = self
                            .find_range_strict(client, None, false, Some(key.clone()), true)
                            .await?;
                        let above = self
                            .find_range_strict(client, Some(key.clone()), true, None, false)
                            .await?;
                        below.extend(above);
                        below
                    }
                    Operator::Gt => {
                        self.find_range_strict(client, Some(key.clone()), true, None, false)
                            .await?
                    }
                    Operator::Lt => {
                        self.find_range_strict(client, None, false, Some(key.clone()), true)
                            .await?
                    }
                    Operator::Ge => {
                        self.find_range_strict(client, Some(key.clone()), false, None, false)
                            .await?
                    }
                    Operator::Le => {
                        self.find_range_strict(client, None, false, Some(key.clone()), false)
                            .await?
                    }
                };
                Ok(results)
            }
        }
    };
}

impl_typed_http_search_index!(i8, KeyType::Int8);
impl_typed_http_search_index!(u8, KeyType::UInt8);
impl_typed_http_search_index!(i16, KeyType::Int16);
impl_typed_http_search_index!(u16, KeyType::UInt16);
impl_typed_http_search_index!(i32, KeyType::Int32);
impl_typed_http_search_index!(i64, KeyType::Int64);
impl_typed_http_search_index!(u32, KeyType::UInt32);
impl_typed_http_search_index!(u64, KeyType::UInt64);
impl_typed_http_search_index!(ordered_float::OrderedFloat<f32>, KeyType::Float32);
impl_typed_http_search_index!(ordered_float::OrderedFloat<f64>, KeyType::Float64);
impl_typed_http_search_index!(bool, KeyType::Bool);
impl_typed_http_search_index!(chrono::DateTime<chrono::Utc>, KeyType::DateTime);
impl_typed_http_search_index!(
    crate::static_btree::key::FixedStringKey<20>,
    KeyType::StringKey20
);
impl_typed_http_search_index!(
    crate::static_btree::key::FixedStringKey<50>,
    KeyType::StringKey50
);
impl_typed_http_search_index!(
    crate::static_btree::key::FixedStringKey<100>,
    KeyType::StringKey100
);

/// Container for multiple HTTP indices keyed by field name
#[derive(Debug)]
#[cfg(not(target_arch = "wasm32"))]
pub struct HttpMultiIndex<T: AsyncHttpRangeClient + Send + Sync> {
    indices: HashMap<String, Box<dyn TypedHttpSearchIndex<T>>>,
}

#[cfg(not(target_arch = "wasm32"))]
impl<T: AsyncHttpRangeClient + Send + Sync> HttpMultiIndex<T> {
    /// Create a new empty HTTP multi-index
    pub fn new() -> Self {
        Self {
            indices: HashMap::new(),
        }
    }

    /// Add an index for any supported key type
    pub fn add_index<K: Key + 'static>(&mut self, field: String, index: HttpIndex<K>)
    where
        HttpIndex<K>: TypedHttpSearchIndex<T> + 'static,
    {
        self.indices.insert(field, Box::new(index));
    }

    /// Execute a multi-condition query by AND-ing all conditions
    pub async fn query(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        conditions: &[QueryCondition],
    ) -> Result<Vec<HttpSearchResultItem>> {
        if conditions.is_empty() {
            return Err(Error::QueryError("query cannot be empty".to_string()));
        }
        let mut result_sets = Vec::with_capacity(conditions.len());
        for cond in conditions {
            let idx = self.indices.get(&cond.field).ok_or_else(|| {
                Error::QueryError(format!("no index found for field '{}'", cond.field))
            })?;
            let items = idx.execute_query_condition(client, cond).await?;
            result_sets.push(items);
            if result_sets.is_empty() {
                // no results found for this condition, return early so we don't waste time intersecting empty sets
                return Ok(vec![]);
            }
        }
        // intersect all sets
        let mut iter = result_sets.into_iter();
        let mut intersection = iter.next().unwrap_or_default();
        for set in iter {
            intersection.retain(|x| set.contains(x));
        }
        Ok(intersection)
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl<T: AsyncHttpRangeClient + Send + Sync> Default for HttpMultiIndex<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Container for multiple HTTP indices keyed by field name (WASM version)
#[derive(Debug)]
#[cfg(target_arch = "wasm32")]
pub struct HttpMultiIndex<T: AsyncHttpRangeClient> {
    indices: HashMap<String, Box<dyn TypedHttpSearchIndex<T>>>,
}

#[cfg(target_arch = "wasm32")]
impl<T: AsyncHttpRangeClient> HttpMultiIndex<T> {
    /// Create a new empty HTTP multi-index
    pub fn new() -> Self {
        Self {
            indices: HashMap::new(),
        }
    }

    /// Add an index for any supported key type
    pub fn add_index<K: Key + 'static>(&mut self, field: String, index: HttpIndex<K>)
    where
        HttpIndex<K>: TypedHttpSearchIndex<T> + 'static,
    {
        self.indices.insert(field, Box::new(index));
    }
    /// Execute a multi-condition query by AND-ing all conditions
    pub async fn query(
        &self,
        client: &mut AsyncBufferedHttpRangeClient<T>,
        conditions: &[QueryCondition],
    ) -> Result<Vec<HttpSearchResultItem>> {
        if conditions.is_empty() {
            return Err(Error::QueryError("query cannot be empty".to_string()));
        }
        let mut result_sets = Vec::with_capacity(conditions.len());

        for cond in conditions {
            // print the field name of condition and indices names

            let idx = self.indices.get(&cond.field).ok_or_else(|| {
                Error::QueryError(format!("no index found for field '{}'", cond.field))
            })?;
            let items = idx.execute_query_condition(client, cond).await?;
            result_sets.push(items);
            if result_sets.is_empty() {
                // no results found for this condition, return early so we don't waste time intersecting empty sets
                return Ok(vec![]);
            }
        }
        // intersect all sets
        let mut iter = result_sets.into_iter();
        let mut intersection = iter.next().unwrap_or_default();
        for set in iter {
            intersection.retain(|x| set.contains(x));
        }
        Ok(intersection)
    }
}

#[cfg(target_arch = "wasm32")]
impl<T: AsyncHttpRangeClient> Default for HttpMultiIndex<T> {
    fn default() -> Self {
        Self::new()
    }
}