A new python geohash library released!

The goal of this article is to explain how you can create your own python library with rust. Rust is not magic but the language have a lot of fresh and new features. Maybe I made a lot of mistakes, don’t hesitate to correct in the coments.

The situation

$ cargo new geohashrs
[package]
name = "geohashrs"
version = "0.1.4"
authors = ["nabil@eml.cc"]
edition = "2018"
license = "Apache-2.0"
repository = "https://github.com/blackrez/geohashrs"
homepage = "https://github.com/blackrez/geohashrs"
readme = "README.md"

[lib]
name = "geohashrs"
crate-type = ["cdylib", "rlib"]

[package.metadata.maturin]
maintainer = "Nabil Servais"
maintainer-email = "nabil@eml.cc"
requires-python = ">=3.5"
classifier = ["Programming Language :: Python"]

[dependencies]
geohash = "0.9.0"

[dependencies.pyo3]
version = "0.11.1"
features = ["extension-module"]

Pyo3 a great binding

/// Encode coords into geohash
#[pyfunction]
fn geohash_encode(x: f64, y: f64, level: usize) -> PyResult<String> {
let c = Coordinate { x: x, y: y };
let geohash_string = geohash::encode(c, level).expect("Invalid coordinate");
Ok(geohash_string)
}

// Decode geohash into Python list
#[pyfunction]
fn geohash_decode(hash: &str) -> PyResult<Vec<f64>> {
let (c, _, _) = decode(&hash).expect("Invalid hash string");
let vec = vec![c.x, c.y];
Ok(vec)
}
#[pymodule]
fn geohashrs(py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(geohash_encode))?;
m.add_wrapped(wrap_pyfunction!(geohash_decode))?;
Ok(())
}

Maturin

$ pip install maturin
$ maturin build

And the publication

$ maturin publish

What’s next ?

Dev & Ops @ Think.fr (Lille) and Roller Derby Player