|
8 | 8 | #![allow(unused_macros)] |
9 | 9 |
|
10 | 10 | use crate::error::{Error, Result}; |
| 11 | +use crate::ttrpc::KeyValue; |
11 | 12 | use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag}; |
12 | 13 | use nix::sys::socket::*; |
| 14 | +use std::collections::HashMap; |
13 | 15 | use std::os::unix::io::RawFd; |
14 | 16 | use std::str::FromStr; |
15 | 17 |
|
@@ -139,3 +141,46 @@ pub const MESSAGE_LENGTH_MAX: usize = 4 << 20; |
139 | 141 |
|
140 | 142 | pub const MESSAGE_TYPE_REQUEST: u8 = 0x1; |
141 | 143 | pub const MESSAGE_TYPE_RESPONSE: u8 = 0x2; |
| 144 | + |
| 145 | +pub fn parse_metadata(kvs: &protobuf::RepeatedField<KeyValue>) -> HashMap<String, Vec<String>> { |
| 146 | + let mut meta: HashMap<String, Vec<String>> = HashMap::new(); |
| 147 | + for kv in kvs { |
| 148 | + if let Some(ref mut vl) = meta.get_mut(&kv.key) { |
| 149 | + vl.push(kv.value.clone()); |
| 150 | + } else { |
| 151 | + meta.insert(kv.key.clone(), vec![kv.value.clone()]); |
| 152 | + } |
| 153 | + } |
| 154 | + meta |
| 155 | +} |
| 156 | + |
| 157 | +#[cfg(test)] |
| 158 | +mod tests { |
| 159 | + use super::parse_metadata; |
| 160 | + use crate::ttrpc::KeyValue; |
| 161 | + |
| 162 | + #[test] |
| 163 | + fn test_parse_metadata() { |
| 164 | + let mut src: protobuf::RepeatedField<KeyValue> = protobuf::RepeatedField::default(); |
| 165 | + for i in &[ |
| 166 | + ("key1", "value1-1"), |
| 167 | + ("key1", "value1-2"), |
| 168 | + ("key2", "value2"), |
| 169 | + ] { |
| 170 | + let mut key = KeyValue::default(); |
| 171 | + key.key = i.0.to_string(); |
| 172 | + key.value = i.1.to_string(); |
| 173 | + src.push(key); |
| 174 | + } |
| 175 | + |
| 176 | + let dst = parse_metadata(&src); |
| 177 | + assert_eq!(dst.len(), 2); |
| 178 | + |
| 179 | + assert_eq!( |
| 180 | + dst.get("key1"), |
| 181 | + Some(&vec!["value1-1".to_string(), "value1-2".to_string()]) |
| 182 | + ); |
| 183 | + assert_eq!(dst.get("key2"), Some(&vec!["value2".to_string()])); |
| 184 | + assert_eq!(dst.get("key3"), None); |
| 185 | + } |
| 186 | +} |
0 commit comments