1//! Defines `MessageKey` struct.
2
3use crate::message::{Message, MessageView};
4
5#[derive(PartialEq, Eq, PartialOrd, Ord)]
6pub(crate) struct MessageKey {
7 key: String,
8}
9
10impl MessageKey {
11 pub(crate) fn gen(msgctxt: Option<&str>, msgid: &str, msgid_plural: Option<&str>) -> Self {
12 Self {
13 key: match (msgctxt, msgid_plural) {
14 (Some(msgctxt: &str), Some(msgid_plural: &str)) => {
15 format!("{}\u{0004}{}\u{0000}{}", msgctxt, msgid, msgid_plural)
16 }
17 (Some(msgctxt: &str), None) => format!("{}\u{0004}{}", msgctxt, msgid),
18 (None, Some(msgid_plural: &str)) => format!("{}\u{0000}{}", msgid, msgid_plural),
19 (None, None) => msgid.to_string(),
20 },
21 }
22 }
23}
24
25impl From<&Message> for MessageKey {
26 fn from(m: &Message) -> Self {
27 match (!m.msgctxt.is_empty(), m.is_plural()) {
28 (true, true) => Self::gen(msgctxt:Some(&m.msgctxt), &m.msgid, msgid_plural:Some(&m.msgid_plural)),
29 (true, false) => Self::gen(msgctxt:Some(&m.msgctxt), &m.msgid, msgid_plural:None),
30 (false, true) => Self::gen(msgctxt:None, &m.msgid, msgid_plural:Some(&m.msgid_plural)),
31 (false, false) => Self::gen(msgctxt:None, &m.msgid, msgid_plural:None),
32 }
33 }
34}
35
36#[cfg(test)]
37mod test {
38 use crate::message::{Message, MessageKey};
39
40 #[test]
41 fn test_singular_message_key_without_ctxt() {
42 let message = Message::build_singular()
43 .with_msgid(String::from("ID"))
44 .done();
45 assert_eq!("ID", MessageKey::from(&message).key);
46 }
47
48 #[test]
49 fn test_singular_message_key_with_ctxt() {
50 let message = Message::build_singular()
51 .with_msgctxt(String::from("CTXT"))
52 .with_msgid(String::from("ID"))
53 .done();
54 assert_eq!("CTXT\u{0004}ID", MessageKey::from(&message).key);
55 }
56}
57