]>
Commit | Line | Data |
---|---|---|
1ea740e9 SS |
1 | #define PERL_NO_GET_CONTEXT |
2 | #include "EXTERN.h" | |
3 | #include "perl.h" | |
4 | #include "XSUB.h" | |
5 | ||
6 | #include <stdio.h> | |
7 | #include <string.h> | |
8 | ||
1ea740e9 SS |
9 | |
10 | #include <loc/libloc.h> | |
11 | #include <loc/database.h> | |
12 | #include <loc/network.h> | |
13 | ||
14 | ||
15 | MODULE = Location PACKAGE = Location | |
16 | ||
17 | struct loc_database * | |
18 | init(file) | |
19 | char * file; | |
20 | ||
21 | CODE: | |
da1039da | 22 | struct loc_ctx* ctx = NULL; |
1ea740e9 | 23 | |
74ad091d | 24 | // Initialise location context |
da1039da | 25 | int err = loc_new(&ctx); |
1ea740e9 | 26 | if (err < 0) |
5242283a | 27 | croak("Could not initialize libloc context: %d\n", err); |
1ea740e9 | 28 | |
74ad091d | 29 | // Open the database file for reading |
1ea740e9 SS |
30 | FILE* f = fopen(file, "r"); |
31 | if (!f) { | |
5242283a MT |
32 | croak("Could not open file for reading: %s: %s\n", |
33 | file, strerror(errno)); | |
1ea740e9 SS |
34 | } |
35 | ||
74ad091d | 36 | // Parse the database |
da1039da | 37 | struct loc_database *db = NULL; |
1ea740e9 SS |
38 | err = loc_database_new(ctx, &db, f); |
39 | if (err) { | |
5242283a | 40 | croak("Could not read database: %s\n", file); |
1ea740e9 SS |
41 | } |
42 | ||
43 | RETVAL = db; | |
44 | OUTPUT: | |
45 | RETVAL | |
46 | ||
47 | char* | |
48 | get_country_code(db, address) | |
da1039da MT |
49 | struct loc_database* db = NULL; |
50 | char* address = NULL; | |
1ea740e9 SS |
51 | |
52 | CODE: | |
53 | int err; | |
da1039da | 54 | const char* country_code = NULL; |
1ea740e9 | 55 | |
74ad091d | 56 | // Lookup network |
1ea740e9 SS |
57 | struct loc_network *network; |
58 | err = loc_database_lookup_from_string(db, address, &network); | |
59 | if (err) { | |
60 | croak("Could not look up for %s\n", address); | |
61 | } | |
62 | ||
63 | country_code = loc_network_get_country_code(network); | |
1ea740e9 SS |
64 | loc_network_unref(network); |
65 | ||
66 | if (!country_code) { | |
5242283a | 67 | croak("Could not get the country code for %s\n", address); |
1ea740e9 SS |
68 | } |
69 | ||
70 | RETVAL = strdup(country_code); | |
71 | OUTPUT: | |
72 | RETVAL | |
73 | ||
74 | ||
75 | ||
76 | char* | |
77 | database_get_vendor(db) | |
da1039da | 78 | struct loc_database* db = NULL; |
1ea740e9 SS |
79 | |
80 | CODE: | |
da1039da | 81 | const char* vendor = NULL; |
1ea740e9 | 82 | |
74ad091d | 83 | // Get vendor |
1ea740e9 | 84 | vendor = loc_database_get_vendor(db); |
1ea740e9 SS |
85 | if (!vendor) { |
86 | croak("Could not retrieve vendor\n"); | |
87 | } | |
88 | ||
89 | RETVAL = strdup(vendor); | |
90 | OUTPUT: | |
91 | RETVAL | |
92 | ||
93 | void | |
94 | DESTROY(db) | |
da1039da MT |
95 | struct loc_database* db = NULL; |
96 | ||
1ea740e9 | 97 | CODE: |
74ad091d | 98 | // Close database |
1ea740e9 | 99 | loc_database_unref(db); |