1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::fmt::{self, Display, Formatter};
use std::str::FromStr;

use crate::timestamp::Timestamp;
use crate::LyricsError;

/// Tags used in LRC which are in the format **[mm:ss.xx]** or **[mm:ss]** to represent time.
#[derive(Debug, PartialOrd, PartialEq, Ord, Eq, Hash, Clone, Copy)]
pub struct TimeTag(Timestamp);

impl TimeTag {
    /// Create a `TimeTag` instance with a number in milliseconds.
    #[inline]
    pub fn new<N: Into<i64>>(timestamp: N) -> TimeTag {
        TimeTag(Timestamp::new(timestamp))
    }

    /// Create a timestamp with a string.
    #[allow(clippy::should_implement_trait)]
    #[inline]
    pub fn from_str<S: AsRef<str>>(timestamp: S) -> Result<TimeTag, LyricsError> {
        let timestamp = timestamp.as_ref();

        let timestamp = if timestamp.starts_with('[') {
            timestamp[1..].trim_start()
        } else {
            timestamp
        };

        let timestamp = if timestamp.ends_with(']') {
            timestamp[..(timestamp.len() - 1)].trim_end()
        } else {
            timestamp
        };

        Ok(TimeTag(Timestamp::from_str(timestamp)?))
    }
}

impl TimeTag {
    /// Get the timestamp in milliseconds.
    #[inline]
    pub fn get_timestamp(self) -> i64 {
        self.0.get_timestamp()
    }
}

impl Display for TimeTag {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
        f.write_fmt(format_args!("[{}]", self.0))
    }
}

impl FromStr for TimeTag {
    type Err = LyricsError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        TimeTag::from_str(s)
    }
}

impl Into<i64> for TimeTag {
    #[inline]
    fn into(self) -> i64 {
        self.0.into()
    }
}