Skip to main content

shaul_core/
link.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::{Error, Result};
6
7/// The raw input supplied by a user: a URL, magnet link, torrent path or Hub
8/// repository reference.
9#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
10#[serde(transparent)]
11pub struct Link(String);
12
13impl Link {
14    /// Trims and validates raw input, rejecting empty links.
15    pub fn new(raw: impl Into<String>) -> Result<Self> {
16        let raw = raw.into();
17        let trimmed = raw.trim();
18        if trimmed.is_empty() {
19            return Err(Error::InvalidLink("link is empty".to_string()));
20        }
21        Ok(Self(trimmed.to_string()))
22    }
23
24    /// Borrows the stored link text.
25    pub fn as_str(&self) -> &str {
26        &self.0
27    }
28
29    /// Stable key used for de-duplicating active tasks.
30    pub fn canonical(&self) -> String {
31        self.0.trim().to_string()
32    }
33}
34
35impl fmt::Display for Link {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str(&self.0)
38    }
39}
40
41impl TryFrom<&str> for Link {
42    type Error = Error;
43
44    fn try_from(value: &str) -> Result<Self> {
45        Link::new(value)
46    }
47}
48
49impl TryFrom<String> for Link {
50    type Error = Error;
51
52    fn try_from(value: String) -> Result<Self> {
53        Link::new(value)
54    }
55}