@@ -170,19 +170,59 @@ pub mod text_propagator;
170170/// underlying struct like `HashMap`.
171171pub trait Carrier {
172172 /// Get a value for a key from the underlying data.
173- fn get ( & self , key : & ' static str ) -> Option < & str > ;
173+ fn get ( & self , key : & str ) -> Option < & str > ;
174174 /// Add a key and value to the underlying.
175- fn set ( & mut self , key : & ' static str , value : String ) ;
175+ fn set ( & mut self , key : & str , value : String ) ;
176176}
177177
178- impl < S : std:: hash:: BuildHasher > api:: Carrier for HashMap < & ' static str , String , S > {
178+ impl < S : std:: hash:: BuildHasher > api:: Carrier for HashMap < String , String , S > {
179179 /// Get a value for a key from the HashMap.
180- fn get ( & self , key : & ' static str ) -> Option < & str > {
180+ fn get ( & self , key : & str ) -> Option < & str > {
181181 self . get ( key) . map ( |v| v. as_str ( ) )
182182 }
183183
184184 /// Set a key and value in the HashMap.
185- fn set ( & mut self , key : & ' static str , value : String ) {
186- self . insert ( key, value) ;
185+ fn set ( & mut self , key : & str , value : String ) {
186+ self . insert ( String :: from ( key) , value) ;
187+ }
188+ }
189+
190+ #[ cfg( feature = "http" ) ]
191+ impl api:: Carrier for http:: HeaderMap {
192+ /// Get a value for a key from the HeaderMap. If the value is not valid ASCII, returns None.
193+ fn get ( & self , key : & str ) -> Option < & str > {
194+ match self . get ( key) {
195+ Some ( val) => match val. to_str ( ) {
196+ Ok ( ascii) => Some ( ascii) ,
197+ Err ( _) => None ,
198+ } ,
199+ None => None ,
200+ }
201+ }
202+
203+ /// Set a key and value in the HeaderMap. Does nothing if the key or value are not valid inputs.
204+ fn set ( & mut self , key : & str , value : String ) {
205+ if let Ok ( name) = http:: header:: HeaderName :: from_bytes ( key. as_bytes ( ) ) {
206+ if let Ok ( val) = http:: header:: HeaderValue :: from_str ( & value) {
207+ self . insert ( name, val) ;
208+ }
209+ }
210+ }
211+ }
212+
213+ #[ cfg( feature = "tonic" ) ]
214+ impl api:: Carrier for tonic:: metadata:: MetadataMap {
215+ /// Get a value for a key from the MetadataMap. If the value can't be converted to &str, returns None
216+ fn get ( & self , key : & str ) -> Option < & str > {
217+ self . get ( key) . and_then ( |metadata| metadata. to_str ( ) . ok ( ) )
218+ }
219+
220+ /// Set a key and value in the MetadataMap. Does nothing if the key or value are not valid inputs
221+ fn set ( & mut self , key : & str , value : String ) {
222+ if let Ok ( key) = tonic:: metadata:: MetadataKey :: from_bytes ( key. to_lowercase ( ) . as_bytes ( ) ) {
223+ if let Ok ( val) = tonic:: metadata:: MetadataValue :: from_str ( & value) {
224+ self . insert ( key, val) ;
225+ }
226+ }
187227 }
188228}
0 commit comments