fetchlet_http/webview/
scheme.rs1#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct WebviewScheme {
10 name: &'static str,
11}
12
13impl WebviewScheme {
14 pub const fn new(name: &'static str) -> Self {
21 let bytes = name.as_bytes();
22 assert!(
23 !bytes.is_empty() && bytes[0].is_ascii_lowercase(),
24 "a webview scheme starts with a lowercase letter"
25 );
26 let mut index = 1;
27 while index < bytes.len() {
28 let byte = bytes[index];
29 assert!(
30 byte.is_ascii_lowercase()
31 || byte.is_ascii_digit()
32 || byte == b'+'
33 || byte == b'-'
34 || byte == b'.',
35 "a webview scheme holds lowercase letters, digits, '+', '-' and '.'"
36 );
37 index += 1;
38 }
39 Self { name }
40 }
41
42 pub const fn name(&self) -> &'static str {
44 self.name
45 }
46
47 pub fn origin(&self) -> String {
49 format!("http://{}.localhost", self.name)
50 }
51
52 pub fn start_url(&self) -> String {
55 if cfg!(any(windows, target_os = "android")) {
56 format!("http://{}.localhost/", self.name)
57 } else {
58 format!("{}://localhost/", self.name)
59 }
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::WebviewScheme;
66
67 #[test]
68 fn the_origin_is_the_same_on_every_platform() {
69 const SCHEME: WebviewScheme = WebviewScheme::new("app");
70 assert_eq!(SCHEME.name(), "app");
71 assert_eq!(SCHEME.origin(), "http://app.localhost");
72 let expected = if cfg!(any(windows, target_os = "android")) {
73 "http://app.localhost/"
74 } else {
75 "app://localhost/"
76 };
77 assert_eq!(SCHEME.start_url(), expected);
78 }
79
80 #[test]
81 #[should_panic(expected = "lowercase")]
82 fn a_name_that_is_no_scheme_is_refused() {
83 WebviewScheme::new("App/");
84 }
85}