+// Returns the country at position pos
+static int loc_database_fetch_country(struct loc_database* db,
+ struct loc_country** country, off_t pos) {
+ if ((size_t)pos >= db->countries_count)
+ return -EINVAL;
+
+ DEBUG(db->ctx, "Fetching country at position %jd\n", pos);
+
+ int r;
+ switch (db->version) {
+ case 0:
+ r = loc_country_new_from_database_v0(db->ctx, db->pool, country, db->countries_v0 + pos);
+ break;
+
+ default:
+ return -1;
+ }
+
+ if (r == 0) {
+ DEBUG(db->ctx, "Got country %s\n", loc_country_get_code(*country));
+ }
+
+ return r;
+}
+
+// Performs a binary search to find the country in the list
+LOC_EXPORT int loc_database_get_country(struct loc_database* db,
+ struct loc_country** country, const char* code) {
+ off_t lo = 0;
+ off_t hi = db->countries_count - 1;
+
+ // Save start time
+ clock_t start = clock();
+
+ while (lo <= hi) {
+ off_t i = (lo + hi) / 2;
+
+ // Fetch country in the middle between lo and hi
+ int r = loc_database_fetch_country(db, country, i);
+ if (r)
+ return r;
+
+ // Check if this is a match
+ const char* cc = loc_country_get_code(*country);
+ int result = strcmp(code, cc);
+
+ if (result == 0) {
+ clock_t end = clock();
+
+ // Log how fast this has been
+ DEBUG(db->ctx, "Found country %s in %.4fms\n", cc,
+ (double)(end - start) / CLOCKS_PER_SEC * 1000);
+
+ return 0;
+ }
+
+ // If it wasn't, we release the country and
+ // adjust our search pointers
+ loc_country_unref(*country);
+
+ if (result > 0) {
+ lo = i + 1;
+ } else
+ hi = i - 1;
+ }
+
+ // Nothing found
+ *country = NULL;
+
+ return 1;
+}
+