text_translator/api/
mod.rs

1use crate::*;
2
3pub mod yandex;
4pub use yandex::Yandex;
5
6/// A trait defining a translate API.
7///
8/// Implements `new()` to return a new API, and `translate()` to translate a text.
9pub trait Api {
10    /// Returns a new API struct, without initiating it.
11    fn new() -> Self;
12
13    /// Translates text between two languages.
14    ///
15    /// Takes in input the selected text and two enums:
16    ///
17    /// - `source_language`: [`InputLanguage`](../enum.InputLanguage.html), representing either automatic language detection or a defined language;
18    /// - `target_language`: [`Language`](../enum.Language.html), representing a defined language to output to.
19    ///
20    /// Returns a `Result` containing either a `String` with the translated text, or an [`Error`](../enum.Error.html) that happened during the process.
21    fn translate(
22        &self,
23        text: String,
24        source_language: InputLanguage,
25        target_language: Language,
26    ) -> Result<String, Error>;
27}
28
29/// Extends [`Api`](trait.Api.html) to implement language detection.
30pub trait ApiDetect: Api {
31    /// Detect the language of the selected text.
32    ///
33    /// ## Inputs
34    ///
35    /// Takes in input only a `String` containing the text.
36    ///
37    /// ## Outputs
38    ///
39    /// The method returns a `Result<Option<Language>, Error>` type:
40    ///
41    /// - if the API was able to detect the language, it will result in an `Ok(Some(detected_language))`.
42    /// - if it failed to detect, it will be an `Ok(None)`.
43    /// - if an error preventing the API to do the detection, it will return an error: `Error(returned_error)`.
44    fn detect(&self, text: String) -> Result<Option<Language>, Error>;
45}
46
47/// Extends [`Api`](trait.Api.html), where the API needs to have an API Key.
48pub trait ApiKey<'a>: Api + Sized {
49    fn set_set(&mut self, key: &'a str);
50
51    fn get_key(&self) -> Option<&'a str>;
52}
53
54trait ApiTranslateResponse {
55    fn get_text(&self) -> String;
56}
57
58trait ApiDetectResponse {
59    fn get_lang(&self) -> Option<Language>;
60}
61
62/// Used on enums representing errors that a call to an API returned.
63pub trait ApiError {
64    /// Converts an error code to the enum variant.
65    fn from_error_code(code: u16) -> Self;
66
67    /// Converts an error variant to the matching error code.
68    fn to_error_code(&self) -> u16;
69}