diff --git a/src/location/GeoIp.zig b/src/location/GeoIp.zig index 9a698ef..a5384ae 100644 --- a/src/location/GeoIp.zig +++ b/src/location/GeoIp.zig @@ -27,37 +27,28 @@ pub fn deinit(self: *GeoIP) void { } pub fn lookup(self: *GeoIP, ip: []const u8) !?Coordinates { + const result = lookupInternal(&self.mmdb, ip) catch return null; + + if (!result.found_entry) return null; + + return try self.extractCoordinates(result); +} + +fn lookupInternal(mmdb: *c.MMDB_s, ip: []const u8) !c.MMDB_lookup_result_s { const ip_z = try std.heap.c_allocator.dupeZ(u8, ip); defer std.heap.c_allocator.free(ip_z); var gai_error: c_int = 0; var mmdb_error: c_int = 0; - const result = c.MMDB_lookup_string(&self.mmdb, ip_z.ptr, &gai_error, &mmdb_error); - - if (gai_error != 0 or mmdb_error != 0) { - return null; - } - - if (!result.found_entry) { - return null; - } - - return try self.extractCoordinates(result); + const result = c.MMDB_lookup_string(mmdb, ip_z.ptr, &gai_error, &mmdb_error); + if (gai_error != 0 or mmdb_error != 0) return error.MMDBLookupError; + return result; } pub fn isUSIP(self: *GeoIP, ip: []const u8) bool { - const ip_z = std.heap.c_allocator.dupeZ(u8, ip) catch return false; - defer std.heap.c_allocator.free(ip_z); - - var gai_error: c_int = 0; - var mmdb_error: c_int = 0; - - const result = c.MMDB_lookup_string(&self.mmdb, ip_z.ptr, &gai_error, &mmdb_error); - - if (gai_error != 0 or mmdb_error != 0 or !result.found_entry) { - return false; - } + const result = lookupInternal(&self.mmdb, ip) catch return false; + if (!result.found_entry) return false; var entry_mut = result.entry; const null_term: [*:0]const u8 = @ptrCast(&[_]u8{0});