1
//! URL types for the C API.
2
//!
3
//! Provides a C-compatible, parsed-URL type. Key types: [`Url`],
4
//! [`UrlParseError`], [`ResultUrlUrlParseError`].
5
//!
6
//! The POD type and the cheap accessors live here in `azul-core` (so consumers
7
//! like `crate::video::VideoSource` can hold a typed `Url` without an
8
//! `azul-layout` dependency). `Url::parse` / `Url::join`, which rely on the
9
//! `url` crate, are gated behind the `url` feature; `azul_layout`'s `http`
10
//! feature enables it. Re-exported as `azul_layout::url`.
11

            
12
use alloc::string::String;
13
#[cfg(not(feature = "std"))]
14
use alloc::string::ToString;
15
use core::fmt;
16

            
17
use azul_css::{impl_result, impl_result_inner, AzString};
18

            
19
/// A parsed URL
20
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
21
#[repr(C)]
22
pub struct Url {
23
    /// The full URL string
24
    pub href: AzString,
25
    /// The scheme (e.g., "https")
26
    pub scheme: AzString,
27
    /// The host (e.g., "example.com")
28
    pub host: AzString,
29
    /// The port number, or 0 if not specified (sentinel value; see `effective_port()`)
30
    pub port: u16,
31
    /// The path (e.g., "/path/to/resource")
32
    pub path: AzString,
33
    /// The query string without '?' (e.g., "key=value")
34
    pub query: AzString,
35
    /// The fragment without '#' (e.g., "section")
36
    pub fragment: AzString,
37
}
38

            
39
/// Error when parsing a URL
40
#[derive(Debug, Clone, PartialEq, Eq)]
41
#[repr(C)]
42
pub struct UrlParseError {
43
    /// Error message
44
    pub message: AzString,
45
}
46

            
47
impl fmt::Display for UrlParseError {
48
25
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49
25
        write!(f, "{}", self.message.as_str())
50
25
    }
51
}
52

            
53
#[cfg(feature = "std")]
54
impl std::error::Error for UrlParseError {}
55

            
56
// FFI-safe Result type for URL parsing
57
impl_result!(
58
    Url,
59
    UrlParseError,
60
    ResultUrlUrlParseError,
61
    copy = false,
62
    [Debug, Clone, PartialEq, Eq]
63
);
64

            
65
impl Url {
66
    /// Parse a URL from a string
67
    ///
68
    /// # Errors
69
    ///
70
    /// Returns a `UrlParseError` if `s` is not a valid absolute URL.
71
    #[cfg(feature = "url")]
72
    pub fn parse(s: &str) -> Result<Self, UrlParseError> {
73
        use ::url::Url as UrlParser;
74

            
75
        let parsed = UrlParser::parse(s).map_err(|e| UrlParseError {
76
            message: AzString::from(e.to_string()),
77
        })?;
78

            
79
        Ok(Self {
80
            href: AzString::from(parsed.as_str().to_string()),
81
            scheme: AzString::from(parsed.scheme().to_string()),
82
            host: AzString::from(parsed.host_str().unwrap_or("").to_string()),
83
            port: parsed.port().unwrap_or(0),
84
            path: AzString::from(parsed.path().to_string()),
85
            query: AzString::from(parsed.query().unwrap_or("").to_string()),
86
            fragment: AzString::from(parsed.fragment().unwrap_or("").to_string()),
87
        })
88
    }
89

            
90
    /// Create a URL from components
91
    #[must_use]
92
176
    pub fn from_parts(scheme: &str, host: &str, port: u16, path: &str) -> Self {
93
176
        let port_str = if port == 0
94
145
            || (scheme == "http" && port == 80)
95
144
            || (scheme == "https" && port == 443)
96
        {
97
158
            String::new()
98
        } else {
99
18
            alloc::format!(":{port}")
100
        };
101

            
102
176
        let href = alloc::format!("{scheme}://{host}{port_str}{path}");
103

            
104
176
        Self {
105
176
            href: AzString::from(href),
106
176
            scheme: AzString::from(scheme.to_string()),
107
176
            host: AzString::from(host.to_string()),
108
176
            port,
109
176
            path: AzString::from(path.to_string()),
110
176
            query: AzString::from(String::new()),
111
176
            fragment: AzString::from(String::new()),
112
176
        }
113
176
    }
114

            
115
    /// Get the full URL as a string slice
116
    #[must_use]
117
55
    pub fn as_str(&self) -> &str {
118
55
        self.href.as_str()
119
55
    }
120

            
121
    /// Check if this is an HTTPS URL
122
    #[must_use]
123
87
    pub fn is_https(&self) -> bool {
124
87
        self.scheme.as_str() == "https"
125
87
    }
126

            
127
    /// Check if this is an HTTP URL
128
    #[must_use]
129
98
    pub fn is_http(&self) -> bool {
130
98
        self.scheme.as_str() == "http"
131
98
    }
132

            
133
    /// Get the effective port (using default ports for http/https)
134
    #[must_use]
135
38
    pub fn effective_port(&self) -> u16 {
136
38
        if self.port != 0 {
137
15
            self.port
138
23
        } else if self.is_https() {
139
2
            443
140
21
        } else if self.is_http() {
141
5
            80
142
        } else {
143
16
            0
144
        }
145
38
    }
146

            
147
    /// Join a relative path to this URL
148
    ///
149
    /// # Errors
150
    ///
151
    /// Returns a `UrlParseError` if this URL's `href` is not parseable as a
152
    /// base, or if `path` cannot be resolved against it.
153
    #[cfg(feature = "url")]
154
    pub fn join(&self, path: &str) -> Result<Self, UrlParseError> {
155
        use ::url::Url as UrlParser;
156

            
157
        let base = UrlParser::parse(self.href.as_str()).map_err(|e| UrlParseError {
158
            message: AzString::from(e.to_string()),
159
        })?;
160

            
161
        let joined = base.join(path).map_err(|e| UrlParseError {
162
            message: AzString::from(e.to_string()),
163
        })?;
164

            
165
        Self::parse(joined.as_str())
166
    }
167

            
168
    /// Stub: `url` feature disabled (the `url` crate is gated behind it).
169
    #[cfg(not(feature = "url"))]
170
    /// # Errors
171
    ///
172
    /// Returns an error: the `url` feature is disabled, so URL parsing is unsupported.
173
15
    pub const fn parse(_s: &str) -> Result<Self, UrlParseError> {
174
15
        Err(UrlParseError {
175
15
            message: AzString::from_const_str("url feature not enabled"),
176
15
        })
177
15
    }
178

            
179
    /// Stub: `url` feature disabled (the `url` crate is gated behind it).
180
    #[cfg(not(feature = "url"))]
181
    /// # Errors
182
    ///
183
    /// Returns an error: the `url` feature is disabled, so URL joining is unsupported.
184
18
    pub const fn join(&self, _path: &str) -> Result<Self, UrlParseError> {
185
18
        Err(UrlParseError {
186
18
            message: AzString::from_const_str("url feature not enabled"),
187
18
        })
188
18
    }
189
}
190

            
191
impl fmt::Display for Url {
192
33
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193
33
        write!(f, "{}", self.href.as_str())
194
33
    }
195
}
196

            
197
#[cfg(test)]
198
#[path = "url_test.rs"]
199
mod url_test;