]> git.ipfire.org Git - location/libloc.git/commitdiff
lua: Add function that returns subnets of a network
authorMichael Tremer <michael.tremer@ipfire.org>
Sat, 6 Apr 2024 11:11:28 +0000 (11:11 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Sat, 6 Apr 2024 11:11:28 +0000 (11:11 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/lua/network.c
tests/lua/main.lua

index 15936f78e6ac18a364ef3e81abd7690f2b1a33ad..2da6a1d6e8837fd8f92fc35d05c54384f1c3d5fb 100644 (file)
@@ -151,6 +151,36 @@ static int Network_has_flag(lua_State* L) {
        return 1;
 }
 
+// Subnets
+
+static int Network_subnets(lua_State* L) {
+       struct loc_network* subnet1 = NULL;
+       struct loc_network* subnet2 = NULL;
+       int r;
+
+       Network* self = luaL_checknetwork(L, 1);
+
+       // Make subnets
+       r = loc_network_subnets(self->network, &subnet1, &subnet2);
+       if (r)
+               return luaL_error(L, "Could not create subnets of %s: %s\n",
+                       loc_network_str(self->network), strerror(errno));
+
+       // Create a new table
+       lua_createtable(L, 2, 0);
+
+       // Create the networks & push them onto the table
+       create_network(L, subnet1);
+       loc_network_unref(subnet1);
+       lua_rawseti(L, -2, 1);
+
+       create_network(L, subnet2);
+       loc_network_unref(subnet2);
+       lua_rawseti(L, -2, 2);
+
+       return 1;
+}
+
 // Reverse Pointer
 
 static int Network_reverse_pointer(lua_State* L) {
@@ -188,6 +218,7 @@ static const struct luaL_Reg Network_functions[] = {
        { "get_family", Network_get_family },
        { "has_flag", Network_has_flag },
        { "reverse_pointer", Network_reverse_pointer },
+       { "subnets", Network_subnets },
        { "__gc", Network_gc },
        { "__tostring", Network_tostring },
        { NULL, NULL },
index b45ab1c41474cdc83b288d55d40d149ea17fd048..e139b2dc2171ee65bb52972dec99b1df15244c29 100755 (executable)
@@ -151,6 +151,24 @@ function test_gc()
        print("GC: " .. collectgarbage("collect"))
 end
 
+function test_subnets()
+       location = require("location")
+
+       -- Open the database
+       db = location.Database.open(ENV_TEST_DATABASE)
+
+       local network = db:lookup("1.1.1.1")
+
+       local subnets = network:subnets()
+
+       luaunit.assertIsTable(subnets)
+       luaunit.assertEquals(#subnets, 2)
+
+       for i, subnet in ipairs(subnets) do
+               print(subnet)
+       end
+end
+
 function test_list_networks()
        location = require("location")