message_format/
lib.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! # Message Format
8//!
9//! This crate provides ICU-style message formatting. This provides
10//! for formatting values taking localization rules into account.
11
12#![warn(missing_docs)]
13#![deny(trivial_numeric_casts,
14        unsafe_code, unstable_features,
15        unused_import_braces, unused_qualifications)]
16
17use std::fmt;
18
19pub mod ast;
20mod parse_message;
21
22use ast::{Format, MessagePart};
23pub use self::parse_message::parse_message;
24
25/// A message that has been localized and can be formatted in a
26/// locale-aware manner.
27pub struct Message {
28    message_parts: Vec<MessagePart>,
29}
30
31impl Message {
32    /// Construct a message from constituent parts.
33    pub fn new(parts: Vec<MessagePart>) -> Self {
34        Message { message_parts: parts }
35    }
36
37    /// Format a message to a stream.
38    pub fn format_message(&self, stream: &mut fmt::Write, args: &Args) -> fmt::Result {
39        for part in &self.message_parts {
40            match *part {
41                MessagePart::String(ref string) => {
42                    try!(stream.write_str(string));
43                }
44                MessagePart::Placeholder => unreachable!(),
45                MessagePart::Format(ref format) => try!(format.format_message_part(stream, args)),
46            }
47        }
48        Ok(())
49    }
50}
51
52struct Arg<'arg> {
53    name: &'arg str,
54    value: &'arg fmt::Display,
55}
56
57///
58pub struct Args<'arg> {
59    args: Vec<Arg<'arg>>,
60}
61
62impl<'arg> Args<'arg> {
63    /// Construct new `Args`
64    pub fn new() -> Self {
65        Args { args: vec![] }
66    }
67
68    ///
69    pub fn get(&self, name: &str) -> Option<&fmt::Display> {
70        self.args.iter().find(|ref a| a.name == name).map(|a| a.value)
71    }
72
73    ///
74    pub fn arg(mut self, name: &'arg str, value: &'arg fmt::Display) -> Self {
75        self.args.push(Arg {
76            name: name,
77            value: value,
78        });
79        self
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    #[test]
86    fn it_works() {}
87}