Skip to main content

falco_plugin/tables/import/
table_input.rs

1use crate::error::as_result::WithLastError;
2use crate::tables::import::traits::{TableAccess, TableMetadata};
3use crate::tables::import::{RawTable, TableInfo};
4use crate::tables::{Key, TablesInput};
5use falco_plugin_api::ss_plugin_state_type;
6use std::ffi::CStr;
7
8impl TablesInput<'_> {
9    /// # Import a table from the Falco plugin API
10    ///
11    /// The key type is verified by the plugin API, so this method will return
12    /// an error on mismatch
13    pub fn get_table<T, K>(&self, name: &CStr) -> Result<T, anyhow::Error>
14    where
15        T: TableAccess<Key = K>,
16        K: Key,
17    {
18        let table = unsafe {
19            (self.get_table)(
20                self.owner,
21                name.as_ptr().cast(),
22                K::TYPE_ID as ss_plugin_state_type,
23            )
24        };
25        if table.is_null() {
26            Err(anyhow::anyhow!("Could not get table {:?}", name)).with_last_error(&self.last_error)
27        } else {
28            // Safety: we pass the data directly from FFI, the framework would never lie to us, right?
29            let table = RawTable { table };
30            let metadata = T::Metadata::new(&table, self)?;
31            Ok(T::new(table, metadata, false))
32        }
33    }
34
35    /// # List the available tables
36    pub fn list_tables(&self) -> &[TableInfo] {
37        let mut num_tables = 0u32;
38        let tables = unsafe { (self.list_tables)(self.owner, &mut num_tables as *mut _) };
39        if tables.is_null() {
40            &[]
41        } else {
42            unsafe { std::slice::from_raw_parts(tables.cast(), num_tables as usize) }
43        }
44    }
45}