|
1 | 1 | extern crate geo;
|
2 | 2 |
|
3 | 3 | use postgres_protocol::types;
|
4 |
| -use self::geo::{Bbox, Point}; |
| 4 | +use self::geo::{Bbox, LineString, Point}; |
5 | 5 | use std::error::Error;
|
6 | 6 |
|
7 | 7 | use types::{FromSql, ToSql, IsNull, Type};
|
@@ -59,3 +59,44 @@ impl ToSql for Bbox<f64> {
|
59 | 59 | accepts!(Type::Box);
|
60 | 60 | to_sql_checked!();
|
61 | 61 | }
|
| 62 | + |
| 63 | +impl FromSql for LineString<f64> { |
| 64 | + fn from_sql(_: &Type, raw: &[u8]) -> Result<Self, Box<Error + Sync + Send>> { |
| 65 | + if raw.len() < 5 { |
| 66 | + return Err("invalid message length".into()); |
| 67 | + } |
| 68 | + |
| 69 | + // let _ = types::bool_from_sql(&raw[0..1])?; // is path open or closed |
| 70 | + let n_points = types::int4_from_sql(&raw[1..5])? as usize; |
| 71 | + let raw_points = &raw[5..raw.len()-1]; |
| 72 | + if raw_points.len() != 16 * n_points { |
| 73 | + return Err("invalid message length".into()); |
| 74 | + } |
| 75 | + |
| 76 | + let mut points = Vec::with_capacity(n_points); |
| 77 | + for n in 0..n_points { |
| 78 | + let x = types::float8_from_sql(&raw[n..n+8])?; |
| 79 | + let y = types::float8_from_sql(&raw[n+8..n+16])?; |
| 80 | + points.push(Point::new(x, y)); |
| 81 | + } |
| 82 | + Ok(LineString(points)) |
| 83 | + } |
| 84 | + |
| 85 | + accepts!(Type::Path); |
| 86 | +} |
| 87 | + |
| 88 | +impl ToSql for LineString<f64> { |
| 89 | + fn to_sql(&self, _: &Type, out: &mut Vec<u8>) -> Result<IsNull, Box<Error + Sync + Send>> { |
| 90 | + let closed = false; // always encode an open path from LineString |
| 91 | + types::bool_to_sql(closed, out); |
| 92 | + types::int4_to_sql(self.0.len() as i32, out); |
| 93 | + for point in &self.0 { |
| 94 | + types::float8_to_sql(point.x(), out); |
| 95 | + types::float8_to_sql(point.y(), out); |
| 96 | + } |
| 97 | + Ok(IsNull::No) |
| 98 | + } |
| 99 | + |
| 100 | + accepts!(Type::Path); |
| 101 | + to_sql_checked!(); |
| 102 | +} |
0 commit comments