Skip to main content

dustr/types/
string.rs

1use crate::helpers::*;
2use ::syn::*;
3
4/// The std lib's `String` type behavior.
5///
6/// We currently use a `CString` from to ingest all `String` values. This might be unsafe if the string
7/// was instantiated by the caller without using rust's instanciation mechanism. In that case, it
8/// would be safe to use a `CStr`. See https://doc.rust-lang.org/std/ffi/struct.CString.html
9pub struct Behavior;
10
11impl super::Behavior for Behavior {
12    fn is(&self, sty: &Type) -> bool {
13        if let Type::Path(tp) = sty {
14            is_same_id(&tp.path, "String")
15        } else {
16            false
17        }
18    }
19    fn imports(&self, _sty: &Type, pkg: &str, _crate_name: &str) -> Vec<String> {
20        vec![
21            "dart:ffi".to_owned(),
22            "dart:convert".to_owned(),
23            "package:ffi/ffi.dart".to_owned(),
24            format!("package:{}/dustr/string.dart", pkg),
25        ]
26    }
27    fn name(&self, _sty: &Type) -> String { "string".to_owned() }
28
29    fn ffi(&self, _sty: &Type) -> String {
30        "Pointer<Utf8>".to_owned()
31    }
32    fn native(&self, _sty: &Type) -> String {
33        "String".to_owned()
34    }
35
36    fn native_to_ffi(&self, _sty: &Type, expr: String) -> String {
37        format!("stringToCString({})", expr)
38    }
39    fn ffi_to_native(&self, _sty: &Type, expr: String) -> String {
40        format!("Utf8.fromUtf8({})", expr)
41    }
42}