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
use crate::{error::RedisError, protocol::utils as protocol_utils, types::RedisValue, utils};
use bytes_utils::Str;
use std::{
  collections::VecDeque,
  convert::{TryFrom, TryInto},
};

/// A struct describing the longitude and latitude coordinates of a GEO command.
#[derive(Clone, Debug)]
pub struct GeoPosition {
  pub longitude: f64,
  pub latitude:  f64,
}

impl PartialEq for GeoPosition {
  fn eq(&self, other: &Self) -> bool {
    utils::f64_eq(self.longitude, other.longitude) && utils::f64_eq(self.latitude, other.latitude)
  }
}

impl Eq for GeoPosition {}

impl From<(f64, f64)> for GeoPosition {
  fn from(d: (f64, f64)) -> Self {
    GeoPosition {
      longitude: d.0,
      latitude:  d.1,
    }
  }
}

impl TryFrom<RedisValue> for GeoPosition {
  type Error = RedisError;

  fn try_from(value: RedisValue) -> Result<Self, Self::Error> {
    let (longitude, latitude): (f64, f64) = value.convert()?;
    Ok(GeoPosition { longitude, latitude })
  }
}

/// Units for the GEO DIST command.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum GeoUnit {
  Meters,
  Kilometers,
  Miles,
  Feet,
}

impl GeoUnit {
  pub(crate) fn to_str(&self) -> Str {
    utils::static_str(match *self {
      GeoUnit::Meters => "m",
      GeoUnit::Kilometers => "km",
      GeoUnit::Feet => "ft",
      GeoUnit::Miles => "mi",
    })
  }
}

/// A struct describing the value inside a GEO data structure.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct GeoValue {
  pub coordinates: GeoPosition,
  pub member:      RedisValue,
}

impl<T> TryFrom<(f64, f64, T)> for GeoValue
where
  T: TryInto<RedisValue>,
  T::Error: Into<RedisError>,
{
  type Error = RedisError;

  fn try_from(v: (f64, f64, T)) -> Result<Self, Self::Error> {
    Ok(GeoValue {
      coordinates: GeoPosition {
        longitude: v.0,
        latitude:  v.1,
      },
      member:      utils::try_into(v.2)?,
    })
  }
}

/// A convenience struct for commands that take one or more GEO values.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MultipleGeoValues {
  inner: Vec<GeoValue>,
}

impl MultipleGeoValues {
  pub fn len(&self) -> usize {
    self.inner.len()
  }

  pub fn inner(self) -> Vec<GeoValue> {
    self.inner
  }
}

impl From<GeoValue> for MultipleGeoValues {
  fn from(d: GeoValue) -> Self {
    MultipleGeoValues { inner: vec![d] }
  }
}

impl From<Vec<GeoValue>> for MultipleGeoValues {
  fn from(d: Vec<GeoValue>) -> Self {
    MultipleGeoValues { inner: d }
  }
}

impl From<VecDeque<GeoValue>> for MultipleGeoValues {
  fn from(d: VecDeque<GeoValue>) -> Self {
    MultipleGeoValues {
      inner: d.into_iter().collect(),
    }
  }
}

/// A typed struct representing the full output of the GEORADIUS (or similar) command.
#[derive(Clone, Debug)]
pub struct GeoRadiusInfo {
  pub member:   RedisValue,
  pub position: Option<GeoPosition>,
  pub distance: Option<f64>,
  pub hash:     Option<i64>,
}

impl Default for GeoRadiusInfo {
  fn default() -> Self {
    GeoRadiusInfo {
      member:   RedisValue::Null,
      position: None,
      distance: None,
      hash:     None,
    }
  }
}

impl PartialEq for GeoRadiusInfo {
  fn eq(&self, other: &Self) -> bool {
    self.member == other.member
      && self.position == other.position
      && self.hash == other.hash
      && utils::f64_opt_eq(&self.distance, &other.distance)
  }
}

impl Eq for GeoRadiusInfo {}

impl GeoRadiusInfo {
  /// Parse the value with context from the calling command.
  pub fn from_redis_value(
    value: RedisValue,
    withcoord: bool,
    withdist: bool,
    withhash: bool,
  ) -> Result<Self, RedisError> {
    if let RedisValue::Array(mut data) = value {
      let mut out = GeoRadiusInfo::default();
      data.reverse();

      if withcoord && withdist && withhash {
        // 4 elements: member, dist, hash, position
        protocol_utils::assert_array_len(&data, 4)?;

        out.member = data.pop().unwrap();
        out.distance = data.pop().unwrap().convert()?;
        out.hash = data.pop().unwrap().convert()?;
        out.position = data.pop().unwrap().convert()?;
      } else if withcoord && withdist {
        // 3 elements: member, dist, position
        protocol_utils::assert_array_len(&data, 3)?;

        out.member = data.pop().unwrap();
        out.distance = data.pop().unwrap().convert()?;
        out.position = data.pop().unwrap().convert()?;
      } else if withcoord && withhash {
        // 3 elements: member, hash, position
        protocol_utils::assert_array_len(&data, 3)?;

        out.member = data.pop().unwrap();
        out.hash = data.pop().unwrap().convert()?;
        out.position = data.pop().unwrap().convert()?;
      } else if withdist && withhash {
        // 3 elements: member, dist, hash
        protocol_utils::assert_array_len(&data, 3)?;

        out.member = data.pop().unwrap();
        out.distance = data.pop().unwrap().convert()?;
        out.hash = data.pop().unwrap().convert()?;
      } else if withcoord {
        // 2 elements: member, position
        protocol_utils::assert_array_len(&data, 2)?;

        out.member = data.pop().unwrap();
        out.position = data.pop().unwrap().convert()?;
      } else if withdist {
        // 2 elements: member, dist
        protocol_utils::assert_array_len(&data, 2)?;

        out.member = data.pop().unwrap();
        out.distance = data.pop().unwrap().convert()?;
      } else if withhash {
        // 2 elements: member, hash
        protocol_utils::assert_array_len(&data, 2)?;

        out.member = data.pop().unwrap();
        out.hash = data.pop().unwrap().convert()?;
      }

      Ok(out)
    } else {
      Ok(GeoRadiusInfo {
        member: value,
        ..Default::default()
      })
    }
  }
}