tphrase 1.0.3

A translatable phrase generator.
Documentation
//! Utility functions
//
// Copyright © 2025 OOTA, Masato
//
// This file is part of TPhrase for Rust.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// OR
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use TPhrase for Rust except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

/// A type of instances that can generate a text. Used by [`select_and_generate_text`]`()`.
pub(crate) trait TextGenerator {
    /// Generate a text.
    ///
    /// # Parameter
    /// - `ext_context`: The external context that has some nonterminals and the substitutions.
    /// - `rng`: The random number generator.
    ///
    /// # Return
    /// A text.
    fn generate<R: crate::RandomNumberGenerator>(
        &self,
        ext_context: &crate::ExtContext,
        rng: &mut R,
    ) -> String;
}

/// Select an item, and a string is generated by it.
///
/// # Generic type
/// - `T`: The type of the items.
///
/// # Parameter
/// - `target`: A set from which an item is selected.
/// - `weights`: `weights[i]` is the sum of `weights[i-1]` and the weight to select `target[i]`.
/// - `equalized_chance`: Equalize the chance to select the items.
/// - `ext_context`: The external context that has some nonterminals and the substitutions.
/// - `rng`: The random number generator that generates random numbers in the range of [0.0, 1.0).
///
/// # Return
/// The generated string.
pub(crate) fn select_and_generate_text<T: crate::TextGenerator, R: crate::RandomNumberGenerator>(
    targets: &[T],
    weights: &[f64],
    equalized_chance: bool,
    ext_context: &crate::ExtContext,
    rng: &mut R,
) -> String {
    if targets.is_empty() {
        "nil".to_string()
    } else if targets.len() == 1 {
        targets[0].generate(ext_context, rng)
    } else {
        let mut r: f64 = rng.next();
        let mut i: usize = 0;
        if equalized_chance {
            i = (r * targets.len() as f64).floor().min(usize::MAX as f64) as usize;
        } else if let Some(x) = weights.last() {
            r *= *x;
            i = weights.partition_point(|&x| x < r);
        }
        if i >= targets.len() {
            i = 0;
        }
        targets[i].generate(ext_context, rng)
    }
}

/// Truncate a text of a phrase syntax to help create a user-friendly error message.
///
/// # Parameter
///  - `it`: Iterator of the source text of a phrase syntax.
///  - `min_len`: The minimum length at truncating.
///
/// # Return
/// The truncated first line (except the line with only spaces) of the phrase syntax.
///
/// # Eample
/// ```rust
/// let src = r#"
///     main = "Hello, " {WORLD}
///     WORLD
///       = world
/// "#;
/// let syntax_result: Result<tphrase::Syntax, _> = tphrase::parse(&mut src.chars());
/// assert!(syntax_result.is_err());
/// if let Err(err) = syntax_result {
///    let err_phrase = tphrase::trunc_syntax(&mut src.chars(), 10);
///    assert_eq!(err_phrase, r#"main = "Hello,..."#);
///    println!("Error in the phase \"{}\":", err_phrase);
///    for err_msg in err.error_messages().iter() {
///        println!("{}", err_msg);
///    }
/// }
/// ```
pub fn trunc_syntax<I: Iterator<Item = char>>(it: &mut I, min_len: usize) -> String {
    // Skip unimportant characters.
    let mut c_opt = it.next();
    while let Some(c) = c_opt {
        if !c.is_whitespace() {
            break;
        }
        c_opt = it.next();
    }
    // Pick up some characters from the first line.
    let mut s = String::new();
    let mut trailing_sapce = String::new();
    let mut count: usize = 0;
    while let Some(c) = c_opt {
        if c == '\n' {
            break;
        }
        if c.is_whitespace() {
            trailing_sapce.push(c);
        } else {
            if !trailing_sapce.is_empty() {
                s += &trailing_sapce;
                trailing_sapce.clear();
            }
            s.push(c);
        }
        c_opt = it.next();
        count += 1;
        if count >= min_len && (c == ' ' || c == '\t' || c == '=' || c == '|' || c == '~') {
            break;
        }
    }
    if c_opt.is_some() {
        s += "...";
    }
    s
}

/// Truncate a text of a phrase syntax to help create a user-friendly error message.
///
/// # Parameter
///  - `s`: The source text of a phrase syntax.
///  - `min_len`: The minimum length at truncating.
///
/// # Return
/// The truncated first line (except the line with only spaces) of the phrase syntax.
///
/// # Eample
/// ```rust
/// let src = r#"
///     main = "Hello, " {WORLD}
///     WORLD
///       = world
/// "#;
/// let syntax_result: Result<tphrase::Syntax, _> = tphrase::parse_str(src);
/// assert!(syntax_result.is_err());
/// if let Err(err) = syntax_result {
///    let err_phrase = tphrase::trunc_syntax_str(src, 10);
///    assert_eq!(err_phrase, r#"main = "Hello,..."#);
///    println!("Error in the phase \"{}\":", err_phrase);
///    for err_msg in err.error_messages().iter() {
///        println!("{}", err_msg);
///    }
/// }
/// ```
pub fn trunc_syntax_str(s: &str, min_len: usize) -> String {
    trunc_syntax(&mut s.chars(), min_len)
}