dlsym 0.0.3

Memory-safe bindings around the platform's dynamic library loading primitives
Documentation
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Typed wrappers (`--wrap`): `&CStr` for C strings, slices for
//! `(pointer, length)` pairs, out-parameters returned, and error codes
//! turned into `Result`.

use std::fmt::Write;

use super::{Emitter, Options, glob, ident, rust_type};
use crate::codegen::ir::{Function, Header, Item, Type};

/// Annotations for the functions matching a glob, parsed from
/// `GLOB:ANNOTATION,...`:
///
/// | Annotation      | Effect                                                          |
/// |-----------------|-----------------------------------------------------------------|
/// | `str`           | every `const char *` parameter becomes `&CStr`                  |
/// | `str=NAME`      | only parameter `NAME` becomes `&CStr`                           |
/// | `str?` / `str?=NAME` | the same, as `Option<&CStr>` (`None` passes null)         |
/// | `slice=PTR/LEN` | `PTR` becomes `&[T]` (`&mut [T]` if not `const`; `u8` for `void` and `char`), and `LEN` is its length |
/// | `out=NAME`      | `NAME` (a `T *`) is removed and its value returned; an [`Owned`](super::Owned) handle comes back as its wrapper, released on every path (`Option` without `ret=`; with `ret=`, a null handle on success is an error) |
/// | `ret=nonzero`   | a non-zero return is `Err(code)`; `Ok` holds the out-parameters |
/// | `ret=negative`  | a negative return is `Err(code)`; `Ok` holds the return value and out-parameters |
/// | `ret=errno`     | a negative return is `Err(std::io::Error::last_os_error())`     |
/// | `ret=static-str`| a returned `const char *` is `Option<&CStr>`, borrowed from the bindings (for strings that live as long as the library, like version strings) |
/// | `safe`          | the wrapper is a safe `fn`: the author asserts the function is sound for any values of the remaining parameters |
///
/// Library functions get the wrapper as a `{name}_rs` method next to the
/// raw one; methods of [`Owned`](super::Owned) handles and C++ objects, and
/// their constructors, use the annotations directly.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Wrap {
    /// Glob (`*`, `?`) of the functions the annotations apply to.
    pub pattern: String,
    /// `str`: every `const char *` parameter.
    pub all_strings: bool,
    /// `str=NAME` parameters.
    pub strings: Vec<String>,
    /// `str?`: every `const char *` parameter, nullable.
    pub all_nullable_strings: bool,
    /// `str?=NAME` parameters.
    pub nullable_strings: Vec<String>,
    /// `slice=PTR/LEN` pairs.
    pub slices: Vec<(String, String)>,
    /// `out=NAME` parameters.
    pub outs: Vec<String>,
    /// How the return value signals errors.
    pub ret: Option<Ret>,
    /// Whether the wrapper is safe to call.
    pub safe: bool,
}

/// How a wrapped function's return value is interpreted; see [`Wrap`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ret {
    /// Zero is success; anything else is the error code.
    NonZero,
    /// Negative values are error codes.
    Negative,
    /// Negative values mean failure, with the reason in `errno`.
    Errno,
    /// A C string that lives as long as the library.
    StaticStr,
}

impl Wrap {
    /// Parses `GLOB:ANNOTATION,...` (see [`Wrap`]).
    pub fn parse(spec: &str) -> Result<Self, String> {
        let (pattern, annotations) = spec
            .split_once(':')
            .ok_or_else(|| format!("expected GLOB:ANNOTATION,..., got {spec:?}"))?;
        let mut w = Wrap {
            pattern: pattern.trim().to_owned(),
            ..Wrap::default()
        };
        for a in annotations
            .split(',')
            .map(str::trim)
            .filter(|a| !a.is_empty())
        {
            let (key, value) = match a.split_once('=') {
                Some((k, v)) => (k.trim(), Some(v.trim())),
                None => (a, None),
            };
            match (key, value) {
                ("str", None) => w.all_strings = true,
                ("str", Some(name)) => w.strings.push(name.to_owned()),
                ("str?", None) => w.all_nullable_strings = true,
                ("str?", Some(name)) => w.nullable_strings.push(name.to_owned()),
                ("slice", Some(pair)) => {
                    let (ptr, len) = pair
                        .split_once('/')
                        .ok_or_else(|| format!("expected slice=PTR/LEN, got {a:?}"))?;
                    w.slices
                        .push((ptr.trim().to_owned(), len.trim().to_owned()));
                }
                ("out", Some(name)) => w.outs.push(name.to_owned()),
                ("ret", Some(kind)) => {
                    w.ret = Some(match kind {
                        "nonzero" => Ret::NonZero,
                        "negative" => Ret::Negative,
                        "errno" => Ret::Errno,
                        "static-str" => Ret::StaticStr,
                        _ => return Err(format!("unknown ret= kind {kind:?} in {spec:?}")),
                    })
                }
                ("safe", None) => w.safe = true,
                _ => return Err(format!("unknown annotation {a:?} in {spec:?}")),
            }
        }
        Ok(w)
    }

    /// Merges the annotations of every spec matching `name`, or `None` if
    /// none does.
    pub(super) fn find(wraps: &[Wrap], name: &str) -> Option<Wrap> {
        let mut found: Option<Wrap> = None;
        for w in wraps.iter().filter(|w| glob(&w.pattern, name)) {
            let m = found.get_or_insert_with(Wrap::default);
            m.all_strings |= w.all_strings;
            m.strings.extend(w.strings.iter().cloned());
            m.all_nullable_strings |= w.all_nullable_strings;
            m.nullable_strings
                .extend(w.nullable_strings.iter().cloned());
            m.slices.extend(w.slices.iter().cloned());
            m.outs.extend(w.outs.iter().cloned());
            m.ret = w.ret.or(m.ret);
            m.safe |= w.safe;
        }
        found
    }
}

/// A wrapper's signature and body pieces.
pub(super) struct Plan {
    /// `, name: Type` for each Rust parameter.
    pub params: String,
    /// Statements before the call.
    pub setup: String,
    /// Statements after the call (taking ownership of out-handles).
    pub post: String,
    /// The C arguments after the skipped ones, as Rust expressions.
    pub args: Vec<String>,
    /// The return type (without ` -> `), and the expression producing it
    /// from `ret` (the raw return value) and the out-parameters.
    pub ret_ty: String,
    pub ret_expr: String,
    /// Whether the call's result is used.
    pub uses_ret: bool,
}

impl Emitter<'_> {
    /// Plans a wrapper for `f`, whose first `skip` parameters are supplied
    /// by the caller (e.g. a handle), and where `lib` is the expression for
    /// the bindings. `Err` if an annotation does not fit (with the reason).
    pub(super) fn plan(
        &self,
        f: &Function,
        skip: usize,
        w: &Wrap,
        lib: &str,
    ) -> Result<Plan, String> {
        let params = &f.params[skip..];
        let names: Vec<String> = params
            .iter()
            .enumerate()
            .map(|(i, p)| p.name.clone().unwrap_or_else(|| format!("arg{}", i + skip)))
            .collect();
        let find = |n: &str| {
            names
                .iter()
                .position(|m| m == n)
                .ok_or_else(|| format!("no parameter `{n}`"))
        };
        // How each C parameter is supplied.
        enum Arg {
            Plain,
            Str,
            OptStr,
            Slice {
                mutable: bool,
                elem: String,
            },
            Len(usize),
            Out(String),
            /// An out-parameter receiving an owned handle (its wrapper).
            OutOwned(String, String),
        }
        let mut how: Vec<Arg> = params.iter().map(|_| Arg::Plain).collect();
        for (i, p) in params.iter().enumerate() {
            let wanted = w.strings.contains(&names[i]);
            let wanted_opt = w.nullable_strings.contains(&names[i]);
            if (w.all_nullable_strings || wanted_opt) && self.is_c_string(&p.ty) {
                how[i] = Arg::OptStr;
            } else if (w.all_strings || wanted) && self.is_c_string(&p.ty) {
                how[i] = Arg::Str;
            } else if wanted || wanted_opt {
                return Err(format!("`{}` is not a `const char *`", names[i]));
            }
        }
        for (ptr, len) in &w.slices {
            let (p, l) = (find(ptr)?, find(len)?);
            let Type::Pointer { pointee, is_const } = self.resolve(&params[p].ty) else {
                return Err(format!("`{ptr}` is not a pointer"));
            };
            if !is_integer(self.resolve(&params[l].ty)) {
                return Err(format!("`{len}` is not an integer"));
            }
            // `char` buffers are bytes (`c_char` is `i8` or `u8` depending on
            // the target).
            let elem = match self.resolve(pointee) {
                Type::Void | Type::Char => "u8".to_owned(),
                _ => rust_type(pointee),
            };
            how[p] = Arg::Slice {
                mutable: !is_const,
                elem,
            };
            how[l] = Arg::Len(p);
        }
        for out in &w.outs {
            let i = find(out)?;
            let Type::Pointer {
                pointee,
                is_const: false,
            } = self.resolve(&params[i].ty)
            else {
                return Err(format!("`{out}` is not a mutable pointer"));
            };
            if **pointee == Type::Void {
                return Err(format!("`{out}` points to `void`"));
            }
            let owned = self
                .owned_wrappers
                .iter()
                .find(|(t, _)| self.handle_param(pointee, t).is_some());
            how[i] = match owned {
                Some((_, wrapper)) => Arg::OutOwned(rust_type(pointee), wrapper.clone()),
                None => Arg::Out(rust_type(pointee)),
            };
        }

        let mut plan = Plan {
            params: String::new(),
            setup: String::new(),
            post: String::new(),
            args: Vec::new(),
            ret_ty: String::new(),
            ret_expr: String::new(),
            uses_ret: true,
        };
        // Out-parameters: name, returned type, and whether it is a handle.
        let mut outs: Vec<(String, String, bool)> = Vec::new();
        for (i, a) in how.iter().enumerate() {
            let n = ident(&names[i]);
            match a {
                Arg::Plain => {
                    let _ = write!(plan.params, ", {n}: {}", rust_type(&params[i].ty));
                    plan.args.push(n);
                }
                Arg::Str => {
                    let _ = write!(plan.params, ", {n}: &::core::ffi::CStr");
                    plan.args.push(format!("{n}.as_ptr()"));
                }
                Arg::OptStr => {
                    let _ = write!(
                        plan.params,
                        ", {n}: ::core::option::Option<&::core::ffi::CStr>"
                    );
                    plan.args.push(format!(
                        "{n}.map_or(::core::ptr::null(), ::core::ffi::CStr::as_ptr)"
                    ));
                }
                Arg::Slice { mutable, elem } => {
                    let (r, m) = if *mutable {
                        ("&mut ", "as_mut_ptr")
                    } else {
                        ("&", "as_ptr")
                    };
                    let _ = write!(plan.params, ", {n}: {r}[{elem}]");
                    plan.args.push(format!("{n}.{m}().cast()"));
                }
                Arg::Len(p) => {
                    let slice = ident(&names[*p]);
                    let ty = rust_type(&params[i].ty);
                    if ty == "usize" {
                        let _ = writeln!(plan.setup, "        let {n} = {slice}.len();");
                    } else {
                        let _ = writeln!(
                            plan.setup,
                            "        let {n} = <{ty}>::try_from({slice}.len()).expect(\"`{slice}` is too long\");"
                        );
                    }
                    plan.args.push(n);
                }
                Arg::Out(ty) => {
                    let _ = writeln!(
                        plan.setup,
                        "        // SAFETY: generated types are valid when zeroed.\n        \
                         let mut {n}: {ty} = unsafe {{ ::core::mem::zeroed() }};"
                    );
                    plan.args.push(format!("&raw mut {n}"));
                    outs.push((n, ty.clone(), false));
                }
                Arg::OutOwned(ty, wrapper) => {
                    let _ = writeln!(
                        plan.setup,
                        "        // SAFETY: generated types are valid when zeroed.\n        \
                         let mut {n}: {ty} = unsafe {{ ::core::mem::zeroed() }};"
                    );
                    plan.args.push(format!("&raw mut {n}"));
                    // Owned right after the call, so that it is released on
                    // every path (some libraries return a handle even on
                    // failure, e.g. `sqlite3_open`).
                    let _ = writeln!(
                        plan.post,
                        "        // SAFETY: `{}` hands over the handle it stores in `{n}`.\n        \
                         let {n} = unsafe {{ {wrapper}::from_raw({lib}, {n}) }};",
                        f.name
                    );
                    outs.push((n, format!("{wrapper}<'_>"), true));
                }
            }
        }

        let raw = (f.ret != Type::Void).then(|| rust_type(&f.ret));
        // `(value, out...)` as a type and an expression.
        let tuple = |with_ret: bool| {
            let mut tys = Vec::new();
            let mut exprs = Vec::new();
            if with_ret && let Some(r) = &raw {
                tys.push(r.clone());
                exprs.push("ret".to_owned());
            }
            for (n, t, handle) in &outs {
                if *handle && w.ret.is_none() {
                    tys.push(format!("::core::option::Option<{t}>"));
                } else {
                    tys.push(t.clone());
                }
                exprs.push(n.clone());
            }
            match tys.len() {
                1 => (tys.remove(0), exprs.remove(0)),
                _ => (
                    format!("({})", tys.join(", ")),
                    format!("({})", exprs.join(", ")),
                ),
            }
        };
        let code = || -> Result<String, String> {
            match self.resolve(&f.ret) {
                t if is_integer(t) => Ok("ret".to_owned()),
                Type::Named(n) if self.enums.contains_key(n.as_str()) => Ok("ret.0".to_owned()),
                _ => Err("ret= needs an integer return type".to_owned()),
            }
        };
        // With `ret=`, the error check also requires every out-handle to be
        // non-null: `match (ok, h1, ..) { (true, Some(h1), ..) => Ok(..), .. }`.
        let handles: Vec<&str> = outs.iter().filter(|o| o.2).map(|o| o.0.as_str()).collect();
        let checked = |cond: String, ok: &str, null_err: &str, err: &str| {
            if handles.is_empty() {
                return format!(
                    "if {cond} {{ ::core::result::Result::Ok({ok}) }} else {{ {err} }}"
                );
            }
            let somes: Vec<String> = handles
                .iter()
                .map(|h| format!("::core::option::Option::Some({h})"))
                .collect();
            format!(
                "match ({cond}, {}) {{\n            \
                     (true, {}) => ::core::result::Result::Ok({ok}),\n            \
                     (true, ..) => {null_err},\n            \
                     _ => {err},\n        \
                 }}",
                handles.join(", "),
                somes.join(", ")
            )
        };
        match w.ret {
            None => {
                let (ty, expr) = tuple(true);
                plan.uses_ret = raw.is_some();
                (plan.ret_ty, plan.ret_expr) = (ty, expr);
            }
            Some(Ret::NonZero) => {
                let c = code()?;
                let (ok, expr) = tuple(false);
                let r = raw.clone().unwrap_or_default();
                plan.ret_ty = format!("::core::result::Result<{ok}, {r}>");
                let err = "::core::result::Result::Err(ret)";
                plan.ret_expr = checked(format!("{c} == 0"), &expr, err, err);
            }
            Some(Ret::Negative) => {
                let c = code()?;
                let (ok, expr) = tuple(true);
                let r = raw.clone().unwrap_or_default();
                plan.ret_ty = format!("::core::result::Result<{ok}, {r}>");
                let err = "::core::result::Result::Err(ret)";
                plan.ret_expr = checked(format!("{c} >= 0"), &expr, err, err);
            }
            Some(Ret::Errno) => {
                let c = code()?;
                let (ok, expr) = tuple(true);
                plan.ret_ty = format!("::std::io::Result<{ok}>");
                plan.ret_expr = checked(
                    format!("{c} >= 0"),
                    &expr,
                    "::core::result::Result::Err(::std::io::Error::other(\"null handle\"))",
                    "::core::result::Result::Err(::dlsym::__private::errno_error())",
                );
            }
            Some(Ret::StaticStr) => {
                if !self.is_c_string(&f.ret) {
                    return Err("ret=static-str needs a `const char *` return type".into());
                }
                let s = "::core::option::Option<&::core::ffi::CStr>";
                let conv = "if ret.is_null() { ::core::option::Option::None } else {\n            \
                            // SAFETY: the library returns a NUL-terminated string that lives as\n            \
                            // long as it does (`ret=static-str`), and `self` borrows the library.\n            \
                            ::core::option::Option::Some(unsafe { ::core::ffi::CStr::from_ptr(ret) })\n        }";
                if outs.is_empty() {
                    (plan.ret_ty, plan.ret_expr) = (s.into(), conv.into());
                } else {
                    let (ty, expr) = tuple(false);
                    plan.ret_ty = format!("({s}, {ty})");
                    plan.ret_expr = format!("({conv}, {expr})");
                }
            }
        }
        Ok(plan)
    }

    /// Whether `ty` is `const char *` (or a typedef of `char`).
    pub(super) fn is_c_string(&self, ty: &Type) -> bool {
        matches!(self.resolve(ty), Type::Pointer { pointee, is_const: true }
            if matches!(self.resolve(pointee), Type::Char | Type::SChar | Type::UChar))
    }

    /// The body of a wrapper calling `call` (a raw method call returning
    /// `Option` if `optional`), in an `unsafe` block if `unsafe_call`.
    pub(super) fn wrapper_body(
        plan: &Plan,
        call: &str,
        optional: bool,
        unsafe_call: bool,
    ) -> String {
        if plan.setup.is_empty()
            && plan.post.is_empty()
            && (plan.ret_expr == "ret" || !plan.uses_ret)
        {
            // Nothing to convert: forward directly.
            let call = if unsafe_call {
                format!(
                    "        // SAFETY: the requirements are the caller's (or declared met).\n        \
                     unsafe {{ {call} }}\n"
                )
            } else {
                format!("        {call}\n")
            };
            return call;
        }
        let q = if optional { "?" } else { "" };
        let call = if unsafe_call {
            format!("unsafe {{ {call} }}{q}")
        } else {
            format!("{call}{q}")
        };
        let mut body = plan.setup.clone();
        if unsafe_call {
            body.push_str("        // SAFETY: the arguments are converted from valid Rust values; the\n        \
                           // remaining requirements are the caller's (or `safe` asserts them).\n");
        }
        let expr = if optional {
            format!("::core::option::Option::Some({})", plan.ret_expr)
        } else {
            plan.ret_expr.clone()
        };
        if plan.uses_ret {
            let _ = writeln!(body, "        let ret = {call};");
        } else {
            let _ = writeln!(body, "        {call};");
        }
        let _ = writeln!(body, "{}        {expr}", plan.post);
        body
    }

    /// The return type of a wrapper (` -> T`, or nothing for `()`).
    pub(super) fn wrapper_ret(plan: &Plan, optional: bool) -> String {
        match (plan.ret_ty.as_str(), optional) {
            ("()", false) | ("", false) => String::new(),
            ("()", true) | ("", true) => " -> ::core::option::Option<()>".into(),
            (t, false) => format!(" -> {t}"),
            (t, true) => format!(" -> ::core::option::Option<{t}>"),
        }
    }

    /// Emits `{name}_rs` wrappers on the bindings struct for functions with
    /// [`Options::wraps`] annotations.
    pub(super) fn wrappers(&mut self, header: &Header, opts: &Options) {
        if opts.wraps.is_empty() {
            return;
        }
        let taken: std::collections::HashSet<&str> = header
            .items
            .iter()
            .filter_map(|i| match i {
                Item::Function(f) => Some(f.name.as_str()),
                Item::Var(v) => Some(v.name.as_str()),
                Item::MacroFn(m) => Some(m.name.as_str()),
                _ => None,
            })
            .collect();
        let mut methods = String::new();
        for item in &header.items {
            let Item::Function(f) = item else { continue };
            let Some(w) = Wrap::find(&opts.wraps, &f.name) else {
                continue;
            };
            let name = format!("{}_rs", f.name);
            if f.variadic || taken.contains(name.as_str()) {
                let _ = writeln!(
                    self.out,
                    "\n// skipped wrapper `{name}`: variadic or name taken"
                );
                continue;
            }
            let plan = match self.plan(f, 0, &w, "self") {
                Ok(p) => p,
                Err(why) => {
                    let _ = writeln!(self.out, "\n// skipped wrapper `{name}`: {why}");
                    continue;
                }
            };
            let optional = opts.optional.iter().any(|p| glob(p, &f.name));
            let raw_safe = !f.variadic && opts.safe.iter().any(|p| glob(p, &f.name));
            let call = format!("self.{}({})", ident(&f.name), plan.args.join(", "));
            let body = Self::wrapper_body(&plan, &call, optional, !raw_safe);
            let ret = Self::wrapper_ret(&plan, optional);
            let (qual, safety) = if w.safe {
                ("", String::new())
            } else {
                (
                    "unsafe ",
                    format!(
                        "    ///\n    /// # Safety\n    ///\n    /// Same as calling `{}`, except for the converted arguments.\n",
                        f.name
                    ),
                )
            };
            let _ = write!(
                methods,
                "    /// [`{0}`](Self::{0}) with Rust types.\n\
                 {safety}    \
                 #[allow(clippy::too_many_arguments)]\n    \
                 pub {qual}fn {1}(&self{2}){ret} {{\n{body}    }}\n\n",
                ident(&f.name),
                ident(&name),
                plan.params,
            );
        }
        if !methods.is_empty() {
            let _ = write!(
                self.out,
                "\nimpl {} {{\n{}}}\n",
                ident(&opts.struct_name),
                methods.trim_end_matches('\n').to_owned() + "\n"
            );
        }
    }
}

fn is_integer(t: &Type) -> bool {
    matches!(
        t,
        Type::Char
            | Type::SChar
            | Type::UChar
            | Type::Short
            | Type::UShort
            | Type::Int
            | Type::UInt
            | Type::Long
            | Type::ULong
            | Type::LongLong
            | Type::ULongLong
            | Type::Fixed(..)
            | Type::USize
            | Type::ISize
    )
}

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

    #[test]
    fn specs() {
        let w = Wrap::parse("gz*: str, slice=buf/len ,out=n,ret=errno,safe").unwrap();
        assert_eq!(w.pattern, "gz*");
        assert!(w.all_strings && w.safe);
        assert_eq!(w.slices, [("buf".to_owned(), "len".to_owned())]);
        assert_eq!(w.outs, ["n"]);
        assert_eq!(w.ret, Some(Ret::Errno));
        let w = Wrap::parse("f:str?,str?=name").unwrap();
        assert!(w.all_nullable_strings && !w.all_strings);
        assert_eq!(w.nullable_strings, ["name"]);
        assert!(Wrap::parse("gzopen").is_err());
        assert!(Wrap::parse("gzopen:slice=buf").is_err());
        assert!(Wrap::parse("gzopen:ret=maybe").is_err());
        assert!(Wrap::parse("gzopen:frobnicate").is_err());

        let all = [
            Wrap::parse("gz*:str").unwrap(),
            Wrap::parse("gzread:slice=buf/len,ret=negative").unwrap(),
        ];
        let m = Wrap::find(&all, "gzread").unwrap();
        assert!(m.all_strings);
        assert_eq!(m.ret, Some(Ret::Negative));
        assert!(Wrap::find(&all, "deflate").is_none());
    }
}