Skip to main content

yo_kv/
geos.rs

1//! The geospatial commands.
2//!
3//! Ten of them, and every one is a sorted set command underneath, because that
4//! is what a geo key is. `GEOADD` is `ZADD` with the coordinates turned into a
5//! score, `GEOPOS` and `GEOHASH` and `GEODIST` are `ZSCORE` with arithmetic on
6//! the answer, and the six search forms are nine `ZRANGEBYSCORE` calls with a
7//! distance filter over the results. Nothing here holds any state a sorted set
8//! does not already hold, which is why `TYPE` on a geo key says `zset` and why a
9//! client can `ZREM` a place out of one.
10//!
11//! # The six search commands are one command
12//!
13//! `GEOSEARCH`, `GEOSEARCHSTORE`, `GEORADIUS`, `GEORADIUS_RO`,
14//! `GEORADIUSBYMEMBER` and `GEORADIUSBYMEMBER_RO` differ in how they spell where
15//! the centre is and whether they are allowed to write. Once the centre, the
16//! shape and the options are parsed there is one search, and it lives in
17//! [`Keyspace::geosearch`]. The store forms run the same search and put the
18//! results in a key instead of handing them back.
19//!
20//! # Why the results are held rather than streamed
21//!
22//! A search cannot answer in order as it goes. The nine boxes are walked in hash
23//! order and the reply is in distance order, so every candidate has to be in
24//! hand before the first one can be written. The wire needs the count before the
25//! members for the same reason every other range command does.
26//!
27//! So there is a [`Scratch`] on the keyspace holding the hits and one byte
28//! buffer with every member's name in it, cleared and refilled per search rather
29//! than allocated per search. A search that found a million points holds a
30//! million until the next one, which is the same trade [`crate::setops`] makes
31//! and for the same reason: the buffer had to exist for the length of the
32//! command anyway.
33//!
34//! # Errors
35//!
36//! `WRONGTYPE` for a key holding something that is not a sorted set, and a
37//! missing key is an empty one everywhere except `GEODIST`, which answers nil
38//! for a key that is not there rather than for a member that is not there, and
39//! `GEORADIUSBYMEMBER`, which needs a member to take its centre from and says so
40//! when it cannot find one.
41
42use yo_common::num::DIGITS_MAX;
43use yo_common::{Code, Error, Result};
44
45use crate::db::Db;
46use crate::elem::Elements;
47use crate::geo::{self, Kind, Shape, Unit};
48use crate::keyspace::Keyspace;
49use crate::strings;
50use crate::zset::{Bound, Zset};
51use crate::zsets::{ZAdd, member_bytes};
52
53/// What Redis says when a search is asked to start from a member it cannot read
54/// a position out of.
55const NO_MEMBER: &str = "could not decode requested zset member";
56
57/// The error for a point the projection does not reach.
58///
59/// The coordinates are printed back with six decimal places, which is `%f` and
60/// is what Redis formats them with, so `GEOADD k 181 38 x` complains about
61/// `181.000000,38.000000` rather than about `181,38`.
62#[must_use]
63pub fn out_of_range(lon: f64, lat: f64) -> Error {
64    yo_alloc::allow(|| {
65        Error::fmt(
66            Code::Invalid,
67            format_args!("invalid longitude,latitude pair {lon:.6},{lat:.6}"),
68        )
69    })
70}
71
72/// The error for a member a search cannot take its centre from.
73#[must_use]
74pub fn no_member() -> Error {
75    Error::new(Code::Invalid, NO_MEMBER)
76}
77
78/// Which way a search orders what it found.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum Sort {
81    /// Nearest first. `ASC`.
82    Near,
83    /// Furthest first. `DESC`.
84    Far,
85}
86
87/// What a search was asked for beyond its shape.
88#[derive(Debug, Clone, Copy, Default)]
89pub struct Limit {
90    /// `ASC` or `DESC`, or nothing, which leaves the results in the order the
91    /// boxes were walked in.
92    pub sort: Option<Sort>,
93    /// `COUNT`, or nothing for all of them.
94    pub count: Option<usize>,
95    /// `ANY`, which stops the walk as soon as `count` are in hand rather than
96    /// finding them all and keeping the nearest.
97    pub any: bool,
98}
99
100impl Limit {
101    /// The ordering the search actually runs with.
102    ///
103    /// A `COUNT` with no `ASC` or `DESC` means the nearest ones, so it implies
104    /// `ASC`. `ANY` is the exception: it says the caller does not care which
105    /// ones, only how many, and sorting would undo the whole point of it.
106    #[must_use]
107    fn ordering(&self) -> Option<Sort> {
108        match self.sort {
109            Some(s) => Some(s),
110            None if self.count.is_some() && !self.any => Some(Sort::Near),
111            None => None,
112        }
113    }
114
115    /// How many the walk may stop at, or nothing if it has to find them all.
116    #[must_use]
117    fn cap(&self) -> Option<usize> {
118        self.any.then_some(self.count).flatten()
119    }
120}
121
122/// One member a search found.
123#[derive(Debug, Clone, Copy)]
124pub struct Hit {
125    /// Where the member's name starts in the scratch buffer.
126    at: usize,
127    /// How long the name is.
128    len: usize,
129    /// The raw score, which is what `WITHHASH` answers.
130    pub score: u64,
131    /// The stored longitude.
132    pub lon: f64,
133    /// The stored latitude.
134    pub lat: f64,
135    /// How far from the centre of the search, in metres.
136    pub metres: f64,
137}
138
139/// The buffers a search fills, kept rather than built per call.
140///
141/// Two of them: the hits, and one run of bytes with every member's name in it.
142/// A name is a slice of the second, which is why [`Hit`] carries an offset and a
143/// length rather than a `Vec<u8>` each. A search over ten thousand points is one
144/// buffer that grows once instead of ten thousand small allocations.
145#[derive(Debug, Default)]
146pub struct Scratch {
147    /// What the search found, in the order the boxes were walked unless it was
148    /// sorted afterwards.
149    hits: Vec<Hit>,
150    /// The names, end to end.
151    names: Vec<u8>,
152}
153
154impl Scratch {
155    /// Everything the last search found, longest to say and cheapest to read.
156    pub fn iter(&self) -> impl Iterator<Item = (&[u8], &Hit)> {
157        self.hits
158            .iter()
159            .map(|h| (&self.names[h.at..h.at + h.len], h))
160    }
161
162    /// How many hits the last search left here.
163    #[must_use]
164    pub fn len(&self) -> usize {
165        self.hits.len()
166    }
167
168    /// Whether the last search found nothing.
169    #[must_use]
170    pub fn is_empty(&self) -> bool {
171        self.hits.is_empty()
172    }
173
174    /// Forget everything, keeping the space.
175    fn clear(&mut self) {
176        self.hits.clear();
177        self.names.clear();
178    }
179
180    /// Remember one point.
181    fn push(&mut self, name: &[u8], score: u64, lon: f64, lat: f64, metres: f64) {
182        let at = self.names.len();
183        self.names.extend_from_slice(name);
184        self.hits.push(Hit {
185            at,
186            len: name.len(),
187            score,
188            lon,
189            lat,
190            metres,
191        });
192    }
193
194    /// Put the hits in distance order and cut them down to `count`.
195    ///
196    /// The cut comes first when there is one, through a selection rather than a
197    /// full sort, because a search over a city with `COUNT 10` should not pay to
198    /// order the other side of the city. Ties between equal distances land in
199    /// whatever order the selection leaves them, which is what a real server's
200    /// `qsort` does too.
201    fn order(&mut self, limit: Limit) {
202        let Some(sort) = limit.ordering() else {
203            self.hits.truncate(limit.count.unwrap_or(usize::MAX));
204            return;
205        };
206        let near = |a: &Hit, b: &Hit| a.metres.total_cmp(&b.metres);
207        let far = |a: &Hit, b: &Hit| b.metres.total_cmp(&a.metres);
208        let want = limit.count.unwrap_or(self.hits.len()).min(self.hits.len());
209        if want < self.hits.len() {
210            match sort {
211                Sort::Near => self.hits.select_nth_unstable_by(want, near),
212                Sort::Far => self.hits.select_nth_unstable_by(want, far),
213            };
214            self.hits.truncate(want);
215        }
216        match sort {
217            Sort::Near => self.hits.sort_unstable_by(near),
218            Sort::Far => self.hits.sort_unstable_by(far),
219        }
220    }
221}
222
223impl Keyspace {
224    /// `GEOADD key [NX|XX] [CH] longitude latitude member [...]`.
225    ///
226    /// Answers what the `ZADD` underneath answers, which is how many members
227    /// were added, or how many were added or moved with `CH`.
228    ///
229    /// Every coordinate is checked before anything is stored, so a call with one
230    /// bad pair in the middle of it leaves the key exactly as it was. Redis does
231    /// the same, and it matters more here than it looks: `GEOADD` is how a whole
232    /// dataset gets loaded, and a partial load with no way to tell where it
233    /// stopped is worse than a refusal.
234    pub fn geoadd<'m, I>(&mut self, key: &[u8], points: I, opts: ZAdd) -> Result<usize>
235    where
236        I: Iterator<Item = (f64, f64, &'m [u8])> + Clone,
237    {
238        for (lon, lat, member) in points.clone() {
239            strings::check_len(key, member.len())?;
240            if geo::score(lon, lat).is_none() {
241                return Err(out_of_range(lon, lat));
242            }
243        }
244        self.zadd(
245            key,
246            points.map(|(lon, lat, m)| {
247                // Checked in the pass above, and nothing between the two passes
248                // can change what a pair of coordinates hashes to.
249                (geo::score(lon, lat).expect("checked") as f64, m)
250            }),
251            opts,
252        )
253    }
254
255    /// `GEOPOS key member [member ...]`.
256    ///
257    /// Hands each position over as it is found rather than collecting them,
258    /// because the reply is as long as the argument list and the wire already
259    /// knows that number. A member that is not there, or whose score is not a
260    /// position anything wrote, gets nothing.
261    pub fn geopos<'m, F>(
262        &mut self,
263        key: &[u8],
264        members: impl Iterator<Item = &'m [u8]>,
265        mut f: F,
266    ) -> Result<()>
267    where
268        F: FnMut(Option<(f64, f64)>),
269    {
270        let Some(at) = self.zset_slot(key)? else {
271            members.for_each(|_| f(None));
272            return Ok(());
273        };
274        let z = self.zset_at(at);
275        for m in members {
276            f(z.score(m).and_then(geo::decode));
277        }
278        Ok(())
279    }
280
281    /// `GEOHASH key member [member ...]`, the same shape one step further on.
282    pub fn geohash<'m, F>(
283        &mut self,
284        key: &[u8],
285        members: impl Iterator<Item = &'m [u8]>,
286        mut f: F,
287    ) -> Result<()>
288    where
289        F: FnMut(Option<&[u8]>),
290    {
291        let Some(at) = self.zset_slot(key)? else {
292            members.for_each(|_| f(None));
293            return Ok(());
294        };
295        let z = self.zset_at(at);
296        for m in members {
297            let text = z
298                .score(m)
299                .and_then(geo::decode)
300                .and_then(|(lon, lat)| geo::geohash(lon, lat));
301            match text {
302                Some(bytes) => f(Some(&bytes)),
303                None => f(None),
304            }
305        }
306        Ok(())
307    }
308
309    /// `GEODIST key member1 member2 [unit]`, in metres whatever the unit was.
310    ///
311    /// The caller divides, because the unit is a wire concern and the number
312    /// this hands back is the one every other distance in the crate is in.
313    ///
314    /// Nothing at all if either member is missing, and nothing for a key that is
315    /// not there, which are the same nil on the wire.
316    pub fn geodist(&mut self, key: &[u8], a: &[u8], b: &[u8]) -> Result<Option<f64>> {
317        let Some(at) = self.zset_slot(key)? else {
318            return Ok(None);
319        };
320        let z = self.zset_at(at);
321        let (Some(sa), Some(sb)) = (z.score(a), z.score(b)) else {
322            return Ok(None);
323        };
324        let (Some(pa), Some(pb)) = (geo::decode(sa), geo::decode(sb)) else {
325            return Ok(None);
326        };
327        Ok(Some(geo::distance(pa.0, pa.1, pb.0, pb.1)))
328    }
329
330    /// Where a member is, for a search that takes its centre from one.
331    ///
332    /// `FROMMEMBER`, and the two `GEORADIUSBYMEMBER` forms. A key that is not
333    /// there answers nothing, because those commands have their own reply for
334    /// that and it is not the error a missing member gets.
335    pub fn geocentre(&mut self, key: &[u8], member: &[u8]) -> Result<Option<(f64, f64)>> {
336        let Some(at) = self.zset_slot(key)? else {
337            return Ok(None);
338        };
339        match self.zset_at(at).score(member).and_then(geo::decode) {
340            Some(xy) => Ok(Some(xy)),
341            None => Err(no_member()),
342        }
343    }
344
345    /// Run a search and leave what it found on the keyspace.
346    ///
347    /// Answers how many hits there are, which is what the wire needs before it
348    /// can write the array header. The hits themselves come from
349    /// [`Keyspace::geohits`], which borrows rather than copies.
350    ///
351    /// The nine boxes are walked in Redis's order and a box that a previous one
352    /// already covered is skipped, which is not an optimisation: at a radius of
353    /// a few thousand kilometres the step is small enough that neighbouring
354    /// boxes come out identical, and walking one twice would report every member
355    /// in it twice.
356    pub fn geosearch(&mut self, key: &[u8], shape: &Shape, limit: Limit) -> Result<usize> {
357        let mut found = std::mem::take(&mut self.geo);
358        found.clear();
359        let outcome = match self.zset_slot(key) {
360            Err(e) => Err(e),
361            Ok(None) => Ok(()),
362            Ok(Some(at)) => {
363                collect(self.zset_at(at), shape, limit, &mut found);
364                Ok(())
365            }
366        };
367        found.order(limit);
368        let n = found.hits.len();
369        self.geo = found;
370        outcome.map(|()| n)
371    }
372
373    /// What the last [`Keyspace::geosearch`] found.
374    #[must_use]
375    pub fn geohits(&self) -> &Scratch {
376        &self.geo
377    }
378
379    /// `GEOSEARCHSTORE`, and the `STORE` and `STOREDIST` forms of `GEORADIUS`.
380    ///
381    /// Answers how many members went into the destination. A search that found
382    /// nothing deletes the destination rather than leaving an empty sorted set
383    /// or leaving the old contents, which is the rule every store form follows.
384    ///
385    /// `dist` is `STOREDIST`, which stores the distance in the shape's unit as
386    /// the score instead of the geohash. The two are not interchangeable: a key
387    /// written with `STOREDIST` is a sorted set of distances and is not a geo
388    /// key any more, and `GEOPOS` on it answers positions somewhere off the
389    /// coast of Africa rather than an error.
390    pub fn geosearchstore(
391        &mut self,
392        dest: &[u8],
393        src: &[u8],
394        shape: &Shape,
395        limit: Limit,
396        dist: bool,
397    ) -> Result<usize> {
398        let n = self.geosearch(src, shape, limit)?;
399        let found = std::mem::take(&mut self.geo);
400        let mut got = Elements::with_capacity(n.max(16));
401        for (name, hit) in found.iter() {
402            let score = if dist {
403                hit.metres / shape.unit.metres()
404            } else {
405                hit.score as f64
406            };
407            let _ = got.insert(name, score);
408        }
409        self.geo = found;
410        let limits = self.zset_limits;
411        let built = Zset::from_elements(got, &limits);
412        Ok(self.put_zset(dest, built))
413    }
414}
415
416impl Db {
417    /// `GEOSEARCHSTORE` and the two `GEORADIUS` store forms, when the source and
418    /// the destination are not on the same stripe.
419    ///
420    /// The search runs on the source's stripe and leaves its hits in that
421    /// stripe's scratch, which is where they are read from while the result is
422    /// built. The sorted set that comes out is put on the destination's stripe
423    /// under that stripe's promotion thresholds, the same way every other store
424    /// form works.
425    ///
426    /// `from` is the member the centre comes from, for the forms that take it
427    /// from one rather than from a pair of coordinates. It is read here, with
428    /// the stripes already held, so that the centre and the members it is
429    /// measured against are the same key at the same moment. A caller that read
430    /// it beforehand would be handing in a point the member may have moved away
431    /// from since.
432    ///
433    /// # Errors
434    ///
435    /// `WRONGTYPE` from the source, which is checked before the destination is
436    /// touched, and the missing member complaint when `from` names a member the
437    /// source does not have.
438    pub fn geosearchstore(
439        &self,
440        dest: &[u8],
441        src: &[u8],
442        from: Option<&[u8]>,
443        shape: &Shape,
444        limit: Limit,
445        dist: bool,
446    ) -> Result<usize> {
447        let (home, onto) = (self.stripe_of(src), self.stripe_of(dest));
448        if home == onto {
449            let mut stripe = self.hold_stripe(home);
450            let shape = recentre(&mut stripe, src, from, shape)?;
451            return stripe.geosearchstore(dest, src, &shape, limit, dist);
452        }
453        // Both at once and in stripe order, since the search leaves its hits in
454        // the source stripe's scratch, the destination's limits decide what is
455        // built from them, and the destination is written from that. The search
456        // runs with both already held, because a scratch that was filled and
457        // then let go of is a scratch the next search on that stripe overwrites.
458        let mut held = self.hold_many([home, onto].into_iter());
459        let shape = recentre(held.stripe_mut(home), src, from, shape)?;
460        let n = held.stripe_mut(home).geosearch(src, &shape, limit)?;
461        let mut got = Elements::with_capacity(n.max(16));
462        for (name, hit) in held.stripe(home).geohits().iter() {
463            let score = if dist {
464                hit.metres / shape.unit.metres()
465            } else {
466                hit.score as f64
467            };
468            let _ = got.insert(name, score);
469        }
470        let limits = held.stripe(onto).zset_limits;
471        let built = Zset::from_elements(got, &limits);
472        Ok(held.stripe_mut(onto).put_zset(dest, built))
473    }
474}
475
476/// The shape with its centre read out of the source, for the search forms whose
477/// centre is a member rather than a pair of coordinates.
478///
479/// Called with the stripe held, which is the whole point of it. A source that is
480/// not there leaves the shape as it came in, since a search on a key that is not
481/// there finds nothing wherever it is pointed.
482fn recentre(
483    stripe: &mut Keyspace,
484    src: &[u8],
485    from: Option<&[u8]>,
486    shape: &Shape,
487) -> Result<Shape> {
488    let mut shape = *shape;
489    if let Some(member) = from
490        && let Some(centre) = stripe.geocentre(src, member)?
491    {
492        (shape.lon, shape.lat) = centre;
493    }
494    Ok(shape)
495}
496
497/// Walk the nine boxes and keep every member the shape covers.
498///
499/// Split out of [`Keyspace::geosearch`] so that the sorted set borrow and the
500/// scratch buffer are two arguments rather than two borrows of the same
501/// keyspace, which they cannot both be.
502fn collect(z: &Zset, shape: &Shape, limit: Limit, out: &mut Scratch) {
503    let search = geo::areas(shape);
504    let cap = limit.cap();
505    let mut digits = [0u8; DIGITS_MAX];
506    // Redis compares each box against the last one it actually walked, and it
507    // starts that at index zero, which means the centre box is never the thing a
508    // neighbour is compared against. Keeping the quirk keeps the duplicate
509    // behaviour identical at radii large enough for the boxes to collide.
510    let mut last = 0usize;
511    for i in 0..search.boxes.len() {
512        let hash = search.boxes[i];
513        if hash.bits == 0 && hash.step == 0 {
514            continue;
515        }
516        if last != 0 && hash == search.boxes[last] {
517            continue;
518        }
519        if cap.is_some_and(|n| out.hits.len() >= n) {
520            break;
521        }
522        let (low, high) = geo::range(hash);
523        let window = z.window_by_score(Bound::closed(low as f64), Bound::open(high as f64));
524        z.walk(window.start, window.len(), false, |m, raw| {
525            if cap.is_some_and(|n| out.hits.len() >= n) {
526                return;
527            }
528            let Some((lon, lat)) = geo::decode(raw) else {
529                return;
530            };
531            let Some(metres) = shape.covers(lon, lat) else {
532                return;
533            };
534            out.push(member_bytes(m, &mut digits), raw as u64, lon, lat, metres);
535        });
536        last = i;
537    }
538}
539
540/// A circle around a point, which is what five of the six search forms want.
541#[must_use]
542pub fn circle(lon: f64, lat: f64, radius: f64, unit: Unit) -> Shape {
543    Shape {
544        lon,
545        lat,
546        kind: Kind::Circle { radius },
547        unit,
548    }
549}
550
551#[cfg(test)]
552mod tests {
553    use super::*;
554    use crate::Clock;
555
556    /// The three places every Redis geo example uses, and one more far enough
557    /// away to be outside every search here.
558    const PLACES: [(f64, f64, &[u8]); 4] = [
559        (13.361389, 38.115556, b"Palermo"),
560        (15.087269, 37.502669, b"Catania"),
561        (12.758489, 38.788135, b"edge"),
562        (2.352222, 48.856613, b"Paris"),
563    ];
564
565    fn ks() -> Keyspace {
566        let mut db = Keyspace::new();
567        let opts = ZAdd::default();
568        db.geoadd(b"g", PLACES.iter().copied(), opts)
569            .expect("the places are all in range");
570        db
571    }
572
573    fn names(db: &Keyspace) -> Vec<Vec<u8>> {
574        db.geohits().iter().map(|(n, _)| n.to_vec()).collect()
575    }
576
577    #[test]
578    fn a_geo_key_is_a_sorted_set_of_hashes() {
579        let mut db = ks();
580        assert_eq!(db.zcard(b"g").expect("a zset"), 4);
581        // The scores a real 8.10.1 has after the same `GEOADD`.
582        assert_eq!(
583            db.zscore(b"g", b"Palermo").expect("a zset"),
584            Some(3_479_099_956_230_698.0)
585        );
586        assert_eq!(
587            db.zscore(b"g", b"Catania").expect("a zset"),
588            Some(3_479_447_370_796_909.0)
589        );
590    }
591
592    #[test]
593    fn nothing_is_stored_when_one_pair_is_out_of_range() {
594        let mut db = Keyspace::new();
595        let bad: [(f64, f64, &[u8]); 2] = [(13.0, 38.0, b"good"), (13.0, 86.0, b"bad")];
596        let err = db
597            .geoadd(b"g", bad.iter().copied(), ZAdd::default())
598            .expect_err("86 is past the projection");
599        assert_eq!(
600            err.message(),
601            "invalid longitude,latitude pair 13.000000,86.000000"
602        );
603        assert_eq!(db.zcard(b"g").expect("a zset"), 0);
604    }
605
606    #[test]
607    fn a_position_comes_back_where_it_went_in_give_or_take_two_metres() {
608        let mut db = ks();
609        let mut got = Vec::new();
610        db.geopos(b"g", [&b"Palermo"[..], b"nope"].into_iter(), |p| {
611            got.push(p)
612        })
613        .expect("a zset");
614        let (lon, lat) = got[0].expect("Palermo is there");
615        assert_eq!(format!("{lon}"), "13.361389338970184");
616        assert_eq!(format!("{lat}"), "38.1155563954963");
617        assert_eq!(got[1], None);
618    }
619
620    #[test]
621    fn the_distance_between_two_members_is_the_one_a_real_server_answers() {
622        let mut db = ks();
623        let d = db
624            .geodist(b"g", b"Palermo", b"Catania")
625            .expect("a zset")
626            .expect("both are there");
627        assert_eq!(format!("{d:.4}"), "166274.1516");
628        assert_eq!(format!("{:.4}", d / Unit::Km.metres()), "166.2742");
629        // One member missing is the same nil as the whole key missing.
630        assert_eq!(db.geodist(b"g", b"Palermo", b"nope").expect("a zset"), None);
631        assert_eq!(db.geodist(b"nope", b"a", b"b").expect("no key"), None);
632    }
633
634    #[test]
635    fn a_hash_string_is_eleven_characters_and_ends_in_a_zero() {
636        let mut db = ks();
637        let mut got: Vec<Option<Vec<u8>>> = Vec::new();
638        db.geohash(
639            b"g",
640            [&b"Palermo"[..], b"Catania", b"nope"].into_iter(),
641            |h| {
642                got.push(h.map(<[u8]>::to_vec));
643            },
644        )
645        .expect("a zset");
646        assert_eq!(got[0].as_deref(), Some(&b"sqc8b49rny0"[..]));
647        assert_eq!(got[1].as_deref(), Some(&b"sqdtr74hyu0"[..]));
648        assert_eq!(got[2], None);
649    }
650
651    #[test]
652    fn a_radius_search_finds_what_is_inside_it_nearest_first() {
653        let mut db = ks();
654        let shape = circle(15.0, 37.0, 200.0, Unit::Km);
655        let limit = Limit {
656            sort: Some(Sort::Near),
657            ..Limit::default()
658        };
659        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 2);
660        assert_eq!(names(&db), [b"Catania".to_vec(), b"Palermo".to_vec()]);
661        // The distances a real server prints for the same search.
662        let hits: Vec<f64> = db.geohits().iter().map(|(_, h)| h.metres).collect();
663        assert_eq!(format!("{:.4}", hits[0] / 1000.0), "56.4413");
664        assert_eq!(format!("{:.4}", hits[1] / 1000.0), "190.4424");
665    }
666
667    #[test]
668    fn a_box_search_reaches_the_corners_a_circle_does_not() {
669        let mut db = ks();
670        let shape = Shape {
671            lon: 13.361389,
672            lat: 38.115556,
673            kind: Kind::Rect {
674                width: 400.0,
675                height: 400.0,
676            },
677            unit: Unit::Km,
678        };
679        let limit = Limit {
680            sort: Some(Sort::Near),
681            ..Limit::default()
682        };
683        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 3);
684        assert_eq!(
685            names(&db),
686            [b"Palermo".to_vec(), b"edge".to_vec(), b"Catania".to_vec()]
687        );
688    }
689
690    #[test]
691    fn a_count_takes_the_nearest_and_desc_takes_the_furthest() {
692        let mut db = ks();
693        let shape = circle(15.0, 37.0, 200.0, Unit::Km);
694        // A `COUNT` on its own means the nearest, with no `ASC` written.
695        let limit = Limit {
696            count: Some(1),
697            ..Limit::default()
698        };
699        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 1);
700        assert_eq!(names(&db), [b"Catania".to_vec()]);
701        let limit = Limit {
702            sort: Some(Sort::Far),
703            count: Some(1),
704            ..Limit::default()
705        };
706        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 1);
707        assert_eq!(names(&db), [b"Palermo".to_vec()]);
708    }
709
710    #[test]
711    fn any_stops_at_the_count_rather_than_finding_the_nearest() {
712        let mut db = ks();
713        let shape = circle(15.0, 37.0, 200.0, Unit::Km);
714        let limit = Limit {
715            count: Some(1),
716            any: true,
717            ..Limit::default()
718        };
719        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 1);
720        // Whichever box came first, which is not necessarily the nearest, and
721        // that is the whole point of the option.
722        assert_eq!(db.geohits().len(), 1);
723    }
724
725    #[test]
726    fn a_search_that_finds_nothing_is_not_an_error() {
727        let mut db = ks();
728        let shape = circle(0.0, 0.0, 1.0, Unit::M);
729        assert_eq!(
730            db.geosearch(b"g", &shape, Limit::default())
731                .expect("a zset"),
732            0
733        );
734        assert!(db.geohits().is_empty());
735        // Nor is a key that is not there.
736        assert_eq!(
737            db.geosearch(b"nope", &shape, Limit::default())
738                .expect("no key"),
739            0
740        );
741    }
742
743    #[test]
744    fn a_search_around_a_member_is_a_search_around_where_it_is() {
745        let mut db = ks();
746        let (lon, lat) = db
747            .geocentre(b"g", b"Palermo")
748            .expect("a zset")
749            .expect("Palermo is there");
750        let shape = circle(lon, lat, 200.0, Unit::Km);
751        let limit = Limit {
752            sort: Some(Sort::Near),
753            ..Limit::default()
754        };
755        assert_eq!(db.geosearch(b"g", &shape, limit).expect("a zset"), 3);
756        assert_eq!(names(&db)[0], b"Palermo".to_vec());
757        // A member that is not there is the error and not a nil, which is what
758        // separates it from a key that is not there.
759        assert!(db.geocentre(b"g", b"nope").is_err());
760        assert_eq!(db.geocentre(b"nope", b"nope").expect("no key"), None);
761    }
762
763    #[test]
764    fn a_store_keeps_the_hashes_and_a_storedist_keeps_the_distances() {
765        let mut db = ks();
766        let shape = circle(15.0, 37.0, 200.0, Unit::Km);
767        let limit = Limit {
768            sort: Some(Sort::Near),
769            ..Limit::default()
770        };
771        assert_eq!(
772            db.geosearchstore(b"d", b"g", &shape, limit, false)
773                .expect("a zset"),
774            2
775        );
776        assert_eq!(
777            db.zscore(b"d", b"Catania").expect("a zset"),
778            Some(3_479_447_370_796_909.0)
779        );
780        // A stored search is still a geo key, so the round trip works.
781        assert_eq!(
782            db.geodist(b"d", b"Palermo", b"Catania")
783                .expect("a zset")
784                .map(|d| format!("{d:.4}")),
785            Some("166274.1516".to_string())
786        );
787        assert_eq!(
788            db.geosearchstore(b"e", b"g", &shape, limit, true)
789                .expect("a zset"),
790            2
791        );
792        let d = db
793            .zscore(b"e", b"Catania")
794            .expect("a zset")
795            .expect("stored");
796        assert_eq!(format!("{d:.4}"), "56.4413");
797    }
798
799    #[test]
800    fn a_store_that_finds_nothing_deletes_what_was_there() {
801        let mut db = ks();
802        let shape = circle(15.0, 37.0, 200.0, Unit::Km);
803        assert_eq!(
804            db.geosearchstore(b"d", b"g", &shape, Limit::default(), false)
805                .expect("a zset"),
806            2
807        );
808        let empty = circle(0.0, 0.0, 1.0, Unit::M);
809        assert_eq!(
810            db.geosearchstore(b"d", b"g", &empty, Limit::default(), false)
811                .expect("a zset"),
812            0
813        );
814        assert_eq!(db.zcard(b"d").expect("no key"), 0);
815    }
816
817    #[test]
818    fn a_store_from_a_member_takes_its_centre_off_the_held_source() {
819        let db = Db::with_clock(Clock::fixed(1_000_000), 8);
820        db.hold(b"g")
821            .geoadd(b"g", PLACES.iter().copied(), ZAdd::default())
822            .expect("the places are all in range");
823        // A destination somewhere other than where the source is, so that the
824        // two stripe path is the one under test.
825        let dest = (0u32..)
826            .map(|i| format!("d{i}").into_bytes())
827            .find(|d| db.stripe_of(d) != db.stripe_of(b"g"))
828            .expect("some name lands on another stripe");
829        // The shape points at nowhere near Sicily, so a result with the two
830        // Sicilian places in it is a centre that came from the member.
831        let shape = circle(0.0, 0.0, 200.0, Unit::Km);
832        let limit = Limit::default();
833        assert_eq!(
834            db.geosearchstore(&dest, b"g", Some(b"Catania"), &shape, limit, false)
835                .expect("a zset"),
836            2
837        );
838        assert!(
839            db.hold(&dest)
840                .zscore(&dest, b"Palermo")
841                .expect("a zset")
842                .is_some()
843        );
844        // A member that is not there is the error, whatever the shape it came
845        // in with says.
846        assert!(
847            db.geosearchstore(&dest, b"g", Some(b"nope"), &shape, limit, false)
848                .is_err()
849        );
850        // And a source that is not there is not, because a search on a key that
851        // is not there finds nothing wherever it is pointed.
852        assert_eq!(
853            db.geosearchstore(&dest, b"gone", Some(b"nope"), &shape, limit, false)
854                .expect("no key"),
855            0
856        );
857    }
858
859    #[test]
860    fn a_search_across_the_date_line_finds_both_sides_of_it() {
861        let mut db = Keyspace::new();
862        let pair: [(f64, f64, &[u8]); 2] = [(179.9, 0.0, b"west"), (-179.9, 0.0, b"east")];
863        db.geoadd(b"d", pair.iter().copied(), ZAdd::default())
864            .expect("both are in range");
865        // The two are 22.2454 kilometres apart going the short way, and a search
866        // that treated longitude as a plain number would find one of them.
867        let d = db
868            .geodist(b"d", b"west", b"east")
869            .expect("a zset")
870            .expect("both are there");
871        assert_eq!(format!("{:.4}", d / Unit::Km.metres()), "22.2454");
872        let shape = circle(179.95, 0.0, 50.0, Unit::Km);
873        assert_eq!(
874            db.geosearch(b"d", &shape, Limit::default())
875                .expect("a zset"),
876            2
877        );
878        // Centred exactly on 180 it finds only the western one, because 180 is
879        // the last longitude the projection has and there is no box east of it
880        // to be a neighbour. A real server answers the same one member, so this
881        // is pinned rather than fixed.
882        let shape = circle(180.0, 0.0, 50.0, Unit::Km);
883        assert_eq!(
884            db.geosearch(b"d", &shape, Limit::default())
885                .expect("a zset"),
886            1
887        );
888        assert_eq!(names(&db), [b"west".to_vec()]);
889    }
890
891    #[test]
892    fn a_key_holding_something_else_is_refused_everywhere() {
893        let mut db = Keyspace::new();
894        db.set(b"s", b"v", strings::SetOptions::default())
895            .expect("a fresh key");
896        let shape = circle(0.0, 0.0, 1.0, Unit::Km);
897        assert_eq!(
898            db.geoadd(b"s", PLACES.iter().copied(), ZAdd::default())
899                .expect_err("a string")
900                .code(),
901            Code::WrongType
902        );
903        assert!(db.geopos(b"s", [&b"x"[..]].into_iter(), |_| {}).is_err());
904        assert!(db.geohash(b"s", [&b"x"[..]].into_iter(), |_| {}).is_err());
905        assert!(db.geodist(b"s", b"a", b"b").is_err());
906        assert!(db.geosearch(b"s", &shape, Limit::default()).is_err());
907        assert!(
908            db.geosearchstore(b"d", b"s", &shape, Limit::default(), false)
909                .is_err()
910        );
911    }
912}