coqui_stt/
token_metadata.rs

1use std::borrow::{Borrow, Cow};
2use std::ffi::CStr;
3use std::fmt::{Debug, Display, Formatter};
4
5/// Stores text of an individual token, along with its timing information.
6#[repr(transparent)]
7pub struct TokenMetadata {
8    ptr: coqui_stt_sys::TokenMetadata,
9}
10
11unsafe impl Send for TokenMetadata {}
12unsafe impl Sync for TokenMetadata {}
13
14impl TokenMetadata {
15    /// The text corresponding to this token
16    #[inline]
17    #[must_use]
18    pub fn text(&self) -> Cow<str> {
19        // SAFETY: self.ptr.text will always point to valid metadata
20        let cstr = unsafe { CStr::from_ptr(self.ptr.text) };
21        cstr.to_string_lossy()
22    }
23
24    /// Position of the token in units of 20ms
25    #[inline]
26    #[must_use]
27    pub const fn timestep(&self) -> u32 {
28        self.ptr.timestep
29    }
30
31    /// Position of the token in seconds
32    #[inline]
33    #[must_use]
34    pub const fn start_time(&self) -> f32 {
35        self.ptr.start_time
36    }
37
38    /// Convert this into an [`OwnedTokenMetadata`](OwnedTokenMetadata) struct.
39    ///
40    /// This is relatively cheap compared to its parent `to_owned` functions,
41    /// as it needs to clone just a `String` and two numbers.
42    #[inline]
43    #[must_use]
44    pub fn to_owned(&self) -> OwnedTokenMetadata {
45        let coqui_stt_sys::TokenMetadata {
46            timestep,
47            start_time,
48            ..
49        } = self.ptr;
50
51        let text = self.text().to_string();
52
53        OwnedTokenMetadata {
54            text,
55            timestep,
56            start_time,
57        }
58    }
59}
60
61impl Debug for TokenMetadata {
62    #[allow(clippy::missing_inline_in_public_items)]
63    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("TokenMetadata")
65            .field("text", &self.text())
66            .field("timestep", &self.timestep())
67            .field("start_time", &self.start_time())
68            .finish()
69    }
70}
71
72impl Display for TokenMetadata {
73    #[inline]
74    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
75        f.write_str(self.text().borrow())
76    }
77}
78
79/// An owned variant of [`TokenMetadata`](TokenMetadata).
80#[non_exhaustive]
81#[derive(Clone, Debug)]
82pub struct OwnedTokenMetadata {
83    /// The text corresponding to this token
84    pub text: String,
85    /// Position of the token in units of 20ms
86    pub timestep: u32,
87    /// Position of the token in seconds
88    pub start_time: f32,
89}
90
91impl Display for OwnedTokenMetadata {
92    #[inline]
93    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
94        f.write_str(&self.text)
95    }
96}