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
//! [![The original comic](https://imgs.xkcd.com/comics/geohashing.png)](https://xkcd.com/426/)

extern crate md5;
extern crate chrono;
use chrono::{Datelike, NaiveDate};
#[cfg(feature="online")]
extern crate reqwest;
#[cfg(feature="online")]
extern crate regex;
#[cfg(feature="online")]
use regex::Regex;

fn bytes_to_f64(hex: &[u8]) -> f64 {
	let mut curvalue = 0.0;

	for (i, c) in hex.iter().enumerate() {
		// first "hex char"
		let mut d1 = (c / 16) as f64;
		let mut d2: f64 = 16.0;
		d2 = d2.powf((i * 2 + 1) as f64);
		curvalue = curvalue + (d1 / d2);

		// second "hex char"
		d1 = (c % 16) as f64;
		d2 = 16.0;
		d2 = d2.powf((i * 2 + 2) as f64);
		curvalue = curvalue + (d1 / d2);
	}

	curvalue
}

#[cfg(feature="offline")]
const DJIA: [((u64, u8, u8), &str); 32785] = include!("djia.txt");

#[cfg(feature="offline")]
fn search_djia_offline(date: NaiveDate) -> Option<&'static str> {
	let year = date.year();
	let month = date.month();
	let day = date.day();
	let date = (year as u64, month as u8, day as u8);
	DJIA.binary_search_by_key(&date, |x| x.0).ok().map(|idx| DJIA[idx].1)
}

#[cfg(feature="online")]
fn search_djia_online(date: NaiveDate) -> Option<String> {
	let year = date.year();
	let month = date.month();
	let day = date.day();
	let client = reqwest::Client::new();

	let djia_format = Regex::new(r#"^\d+\.\d+$"#).unwrap();

	let url = format!("http://geo.crox.net/djia/{}/{:02}/{:02}", year, month, day);
	if let Some(djia) = client.get(&url).send().map(|mut x| x.text().ok()).ok().unwrap_or(None) {
		if djia_format.is_match(&djia) {
			return Some(djia);
		}
	}

	let url = format!("http://carabiner.peeron.com/xkcd/map/data/{}/{:02}/{:02}", year, month, day);
	
	if let Some(djia) = client.get(&url).send().map(|mut x| x.text().ok()).ok().unwrap_or(None) {
		if djia_format.is_match(&djia) {
			return Some(djia);
		}
	}

	None
}

#[derive(Debug)]
pub enum Error {
	#[cfg(feature="offline")]
	NotInOfflineData,
	#[cfg(feature="online")]
	NetworkError,
	#[cfg(not(any(feature="online", feature="offline")))]
	NoDataSource
}

#[allow(unreachable_code)]
pub fn search_djia(date: NaiveDate) -> Result<String, Error> {
	#[cfg(feature="offline")]
	{
		if let Some(djia) = search_djia_offline(date) {
			return Ok(djia.to_owned());
		}
	}
	#[cfg(feature="online")]
	{
		if let Some(djia) = search_djia_online(date) {
			return Ok(djia.to_owned());
		} else {
			return Err(Error::NetworkError);
		}
	}
	#[cfg(feature="offline")]
	{
		return Err(Error::NotInOfflineData);
	}

	#[cfg(not(any(feature="online", feature="offline")))]
	{
		Err(Error::NoDataSource)
	}
}

/// Get the coordinates of the geohash on that day. Fully W30 compliant.
pub fn get_geohash(date: NaiveDate, (lat, lon): (f64, f64)) -> Option<(f64, f64)> {
	let djia = if lon > -30.0 && date >= NaiveDate::from_ymd(2008, 5, 27) {
		search_djia(date.pred()).ok()
	} else {
		search_djia(date).ok()
	}?;

	let (lat_offset, lon_offset) = djia_to_hash(date, &djia);
	if lon < 0.0 {
		Some((lat+lat_offset, lon-lon_offset))
	} else {
		Some((lat+lat_offset, lon+lon_offset))
	}
}

/// Get the coordinates of the globalhash on that day.
pub fn get_globalhash(date: NaiveDate) -> Option<(f64, f64)> {
	let djia = search_djia(date.pred()).ok()?;

	Some(djia_to_globalhash(date, &djia))
}

pub fn djia_to_hash(date: NaiveDate, djia: &str) -> (f64, f64) {
	let md5 = md5::compute(format!("{}-{:02}-{:02}-{}", date.year(), date.month(), date.day(), djia));

	(bytes_to_f64(&md5[0..8]), bytes_to_f64(&md5[8..]))
}

pub fn djia_to_globalhash(date: NaiveDate, djia: &str) -> (f64, f64) {
	let md5 = md5::compute(format!("{}-{:02}-{:02}-{}", date.year(), date.month(), date.day(), djia));

	(bytes_to_f64(&md5[0..8]) * 180.0 - 90.0, bytes_to_f64(&md5[8..]) * 360.0 - 180.0)
}

/*
fn main() {
	let target_lat = 0.00579;
	let target_lon = 0.38112;
	let mut min_dist = 10000.0;
	let mut min_date = String::new();
	let mut stdout = std::io::stdout();
	for year in 2018..=2018 {
		for month in 7..=7 {
			for day in 4..=4 {
				let date = format!("{}-{:02}-{:02}", year, month, day);

				let djia = search_djia((year, month, day));
				if djia.is_err() {
					continue;
				}
				let djia = djia.unwrap();

				let md5 = md5::compute(format!("{}-{}", date, djia));

				let lat = bytes_to_f64(&md5[0..8]);
				let lon = bytes_to_f64(&md5[8..]);

				let dist = ((target_lat - lat).powf(2.0) + (target_lon - lon).powf(2.0)).sqrt();

				//stdout.write_all(&[b'.']).unwrap();
				//stdout.flush().ok().expect("Could not flush stdout");
				if dist < min_dist {
					min_dist = dist;
					println!();
					println!("{} - {} - {} {} - {:?}", date, dist, lat, lon, djia);
					min_date = date;
				}
			}
		}
	}
	println!();
	println!("-> {}", min_date);
	//println!("</Document></kml>");
}
*/