darkfi_serial/types/
url.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::io::{Error, Read, Result, Write};
20use url::Url;
21
22#[cfg(feature = "async")]
23use crate::{AsyncDecodable, AsyncEncodable};
24#[cfg(feature = "async")]
25use async_trait::async_trait;
26#[cfg(feature = "async")]
27use futures_lite::{AsyncRead, AsyncWrite};
28
29use crate::{Decodable, Encodable};
30
31impl Encodable for Url {
32    fn encode<S: Write>(&self, s: &mut S) -> Result<usize> {
33        self.as_str().encode(s)
34    }
35}
36
37#[cfg(feature = "async")]
38#[async_trait]
39impl AsyncEncodable for Url {
40    async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
41        self.as_str().encode_async(s).await
42    }
43}
44
45impl Decodable for Url {
46    fn decode<D: Read>(d: &mut D) -> Result<Self> {
47        let s: String = Decodable::decode(d)?;
48        match Url::parse(&s) {
49            Ok(v) => Ok(v),
50            Err(e) => Err(Error::other(e)),
51        }
52    }
53}
54
55#[cfg(feature = "async")]
56#[async_trait]
57impl AsyncDecodable for Url {
58    async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
59        let s: String = AsyncDecodable::decode_async(d).await?;
60        match Url::parse(&s) {
61            Ok(v) => Ok(v),
62            Err(e) => Err(Error::other(e)),
63        }
64    }
65}