atc_router/ffi/
router.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use crate::context::Context;
use crate::ffi::ERR_BUF_MAX_LEN;
use crate::router::Router;
use crate::schema::Schema;
use std::cmp::min;
use std::ffi;
use std::os::raw::c_char;
use std::slice::from_raw_parts_mut;
use uuid::Uuid;

/// Create a new router object associated with the schema.
///
/// # Arguments
///
/// - `schema`: a valid pointer to the [`Schema`] object returned by [`schema_new`].
///
/// # Errors
///
/// This function never fails.
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `schema` must be a valid pointer returned by [`schema_new`].
#[no_mangle]
pub unsafe extern "C" fn router_new(schema: &Schema) -> *mut Router {
    Box::into_raw(Box::new(Router::new(schema)))
}

/// Deallocate the router object.
///
/// # Errors
///
/// This function never fails.
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `router` must be a valid pointer returned by [`router_new`].
#[no_mangle]
pub unsafe extern "C" fn router_free(router: *mut Router) {
    drop(Box::from_raw(router));
}

/// Add a new matcher to the router.
///
/// # Arguments
///
/// - `router`: a pointer to the [`Router`] object returned by [`router_new`].
/// - `priority`: the priority of the matcher, higher value means higher priority,
///   and the matcher with the highest priority will be executed first.
/// - `uuid`: the C-style string representing the UUID of the matcher.
/// - `atc`: the C-style string representing the ATC expression.
/// - `errbuf`: a buffer to store the error message.
/// - `errbuf_len`: a pointer to the length of the error message buffer.
///
/// # Returns
///
/// Returns `true` if the matcher was added successfully, otherwise `false`,
/// and the error message will be stored in the `errbuf`,
/// and the length of the error message will be stored in `errbuf_len`.
///
/// # Errors
///
/// This function will return `false` if the matcher could not be added to the router,
/// such as duplicate UUID, and invalid ATC expression.
///
/// # Panics
///
/// This function will panic when:
///
/// - `uuid` doesn't point to a ASCII sequence representing a valid 128-bit UUID.
/// - `atc` doesn't point to a valid C-style string.
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `router` must be a valid pointer returned by [`router_new`].
/// - `uuid` must be a valid pointer to a C-style string, must be properly aligned,
///    and must not have '\0' in the middle.
/// - `atc` must be a valid pointer to a C-style string, must be properly aligned,
///    and must not have '\0' in the middle.
/// - `errbuf` must be valid to read and write for `errbuf_len * size_of::<u8>()` bytes,
///    and it must be properly aligned.
/// - `errbuf_len` must be valid to read and write for `size_of::<usize>()` bytes,
///    and it must be properly aligned.
#[no_mangle]
pub unsafe extern "C" fn router_add_matcher(
    router: &mut Router,
    priority: usize,
    uuid: *const i8,
    atc: *const i8,
    errbuf: *mut u8,
    errbuf_len: *mut usize,
) -> bool {
    let uuid = ffi::CStr::from_ptr(uuid as *const c_char).to_str().unwrap();
    let atc = ffi::CStr::from_ptr(atc as *const c_char).to_str().unwrap();
    let errbuf = from_raw_parts_mut(errbuf, ERR_BUF_MAX_LEN);

    let uuid = Uuid::try_parse(uuid).expect("invalid UUID format");

    if let Err(e) = router.add_matcher(priority, uuid, atc) {
        let errlen = min(e.len(), *errbuf_len);
        errbuf[..errlen].copy_from_slice(&e.as_bytes()[..errlen]);
        *errbuf_len = errlen;
        return false;
    }

    true
}

/// Remove a matcher from the router.
///
/// # Arguments
/// - `router`: a pointer to the [`Router`] object returned by [`router_new`].
/// - `priority`: the priority of the matcher to be removed.
/// - `uuid`: the C-style string representing the UUID of the matcher to be removed.
///
/// # Returns
///
/// Returns `true` if the matcher was removed successfully, otherwise `false`,
/// such as when the matcher with the specified UUID doesn't exist or
/// the priority doesn't match the UUID.
///
/// # Panics
///
/// This function will panic when `uuid` doesn't point to a ASCII sequence
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `router` must be a valid pointer returned by [`router_new`].
/// - `uuid` must be a valid pointer to a C-style string, must be properly aligned,
///    and must not have '\0' in the middle.
#[no_mangle]
pub unsafe extern "C" fn router_remove_matcher(
    router: &mut Router,
    priority: usize,
    uuid: *const i8,
) -> bool {
    let uuid = ffi::CStr::from_ptr(uuid as *const c_char).to_str().unwrap();
    let uuid = Uuid::try_parse(uuid).expect("invalid UUID format");

    router.remove_matcher(priority, uuid)
}

/// Execute the router with the context.
///
/// # Arguments
///
/// - `router`: a pointer to the [`Router`] object returned by [`router_new`].
/// - `context`: a pointer to the [`Context`] object.
///
/// # Returns
///
/// Returns `true` if found a match, `false` means no match found.
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `router` must be a valid pointer returned by [`router_new`].
/// - `context` must be a valid pointer returned by [`context_new`],
///    and must be reset by [`context_reset`] before calling this function
///    if you want to reuse the same context for multiple matches.
#[no_mangle]
pub unsafe extern "C" fn router_execute(router: &Router, context: &mut Context) -> bool {
    router.execute(context)
}

/// Get the de-duplicated fields that are actually used in the router.
/// This is useful when you want to know what fields are actually used in the router,
/// so you can generate their values on-demand.
///
/// # Arguments
///
/// - `router`: a pointer to the [`Router`] object returned by [`router_new`].
/// - `fields`: a pointer to an array of pointers to the field names
///    (NOT C-style strings) that are actually used in the router, which will be filled in.
///    if `fields` is `NULL`, this function will only return the number of fields used
///    in the router.
/// - `fields_len`: a pointer to an array of the length of each field name.
///
/// # Lifetimes
///
/// The string pointers stored in `fields` might be invalidated if any of the following
/// operations are happened:
///
/// - The `router` was deallocated.
/// - A new matcher was added to the `router`.
/// - A matcher was removed from the `router`.
///
/// # Returns
///
/// Returns the number of fields that are actually used in the router.
///
/// # Errors
///
/// This function never fails.
///
/// # Safety
///
/// Violating any of the following constraints will result in undefined behavior:
///
/// - `router` must be a valid pointer returned by [`router_new`].
/// - If `fields` is not `NULL`, `fields` must be valid to read and write for
///   `fields_len * size_of::<*const u8>()` bytes, and it must be properly aligned.
/// - If `fields` is not `NULL`, `fields_len` must be valid to read and write for
///   `size_of::<usize>()` bytes, and it must be properly aligned.
/// - DO NOT write the memory pointed by the elements of `fields`.
/// - DO NOT access the memory pointed by the elements of `fields`
///   after it becomes invalid, see the `Lifetimes` section.
#[no_mangle]
pub unsafe extern "C" fn router_get_fields(
    router: &Router,
    fields: *mut *const u8,
    fields_len: *mut usize,
) -> usize {
    if !fields.is_null() {
        assert!(!fields_len.is_null());
        assert!(*fields_len >= router.fields.len());

        let fields = from_raw_parts_mut(fields, *fields_len);
        let fields_len = from_raw_parts_mut(fields_len, *fields_len);

        for (i, k) in router.fields.keys().enumerate() {
            fields[i] = k.as_bytes().as_ptr();
            fields_len[i] = k.len()
        }
    }

    router.fields.len()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_long_error_message() {
        unsafe {
            let schema = Schema::default();
            let mut router = Router::new(&schema);
            let uuid = ffi::CString::new("a921a9aa-ec0e-4cf3-a6cc-1aa5583d150c").unwrap();
            let junk = ffi::CString::new(vec![b'a'; ERR_BUF_MAX_LEN * 2]).unwrap();
            let mut errbuf = vec![b'X'; ERR_BUF_MAX_LEN];
            let mut errbuf_len = ERR_BUF_MAX_LEN;

            let result = router_add_matcher(
                &mut router,
                1,
                uuid.as_ptr() as *const i8,
                junk.as_ptr() as *const i8,
                errbuf.as_mut_ptr(),
                &mut errbuf_len,
            );
            assert_eq!(result, false);
            assert_eq!(errbuf_len, ERR_BUF_MAX_LEN);
        }
    }

    #[test]
    fn test_short_error_message() {
        unsafe {
            let schema = Schema::default();
            let mut router = Router::new(&schema);
            let uuid = ffi::CString::new("a921a9aa-ec0e-4cf3-a6cc-1aa5583d150c").unwrap();
            let junk = ffi::CString::new("aaaa").unwrap();
            let mut errbuf = vec![b'X'; ERR_BUF_MAX_LEN];
            let mut errbuf_len = ERR_BUF_MAX_LEN;

            let result = router_add_matcher(
                &mut router,
                1,
                uuid.as_ptr() as *const i8,
                junk.as_ptr() as *const i8,
                errbuf.as_mut_ptr(),
                &mut errbuf_len,
            );
            assert_eq!(result, false);
            assert!(errbuf_len < ERR_BUF_MAX_LEN);
        }
    }
}