membrane/
utils.rs

1use crate::SourceCodeLocation;
2use allo_isolate::Isolate;
3use serde::ser::Serialize;
4
5pub fn send<T: Serialize, E: Serialize>(isolate: Isolate, result: Result<T, E>) -> bool {
6  match result {
7    Ok(value) => {
8      if let Ok(buffer) = crate::bincode::serialize(&(crate::MembraneMsgKind::Ok as u8, value)) {
9        isolate.post(crate::allo_isolate::ZeroCopyBuffer(buffer))
10      } else {
11        false
12      }
13    }
14    Err(err) => {
15      if let Ok(buffer) = crate::bincode::serialize(&(crate::MembraneMsgKind::Error as u8, err)) {
16        isolate.post(crate::allo_isolate::ZeroCopyBuffer(buffer))
17      } else {
18        false
19      }
20    }
21  }
22}
23
24pub(crate) fn display_code_location(location: Option<&Vec<SourceCodeLocation>>) -> String {
25  match location {
26    Some(loc) if !loc.is_empty() => {
27      let last = loc.len() - 1;
28      format!(
29        " at {}",
30        loc
31          .iter()
32          .enumerate()
33          .map(|(index, path)| {
34            if last == 0 {
35              // single item
36              path.to_string()
37            } else if index == 0 && last == 1 {
38              // on the first of two
39              format!("{} and", path)
40            } else if index == 1 && last == 1 {
41              // on the second of two
42              path.to_string()
43            } else if index == (last - 1) {
44              // on the next to last of many
45              format!("{}, and", path)
46            } else if index == last {
47              // on the last of many
48              path.to_string()
49            } else {
50              format!("{},", path)
51            }
52          })
53          .collect::<Vec<String>>()
54          .join(" ")
55      )
56    }
57    _ => String::new(),
58  }
59}
60
61pub(crate) fn new_style_export<S: AsRef<str>>(namespace: S, config: &crate::DartConfig) -> bool {
62  !config.v1_import_style.contains(&namespace.as_ref())
63}
64
65#[cfg(test)]
66mod tests {
67  use super::display_code_location;
68
69  #[test]
70  fn test_source_code_display_location() {
71    assert_eq!(display_code_location(Some(&vec![])), "");
72
73    assert_eq!(
74      display_code_location(Some(&vec!["app.rs:30"])),
75      " at app.rs:30"
76    );
77
78    assert_eq!(
79      display_code_location(Some(&vec!["app.rs:30", "foo.rs:10"])),
80      " at app.rs:30 and foo.rs:10"
81    );
82
83    assert_eq!(
84      display_code_location(Some(&vec!["app.rs:30", "foo.rs:10", "bar.rs:5"])),
85      " at app.rs:30, foo.rs:10, and bar.rs:5"
86    );
87  }
88}