@@ -6,10 +6,10 @@ use sqlx::{
66 Decode , Encode , Postgres ,
77 encode:: IsNull ,
88 error:: BoxDynError ,
9- postgres:: { PgArgumentBuffer , PgTypeInfo , PgValueRef } ,
9+ postgres:: { PgArgumentBuffer , PgHasArrayType , PgTypeInfo , PgValueRef } ,
1010 prelude:: * ,
1111} ;
12- use std:: { io:: Write , str:: FromStr } ;
12+ use std:: { borrow :: Cow , io:: Write , str:: FromStr } ;
1313
1414/// validated crate name
1515///
@@ -31,7 +31,14 @@ use std::{io::Write, str::FromStr};
3131 SerializeDisplay ,
3232 bincode:: Encode ,
3333) ]
34- pub struct KrateName ( String ) ;
34+ pub struct KrateName ( Cow < ' static , str > ) ;
35+
36+ impl KrateName {
37+ #[ cfg( test) ]
38+ pub ( crate ) const fn from_static ( s : & ' static str ) -> Self {
39+ KrateName ( Cow :: Borrowed ( s) )
40+ }
41+ }
3542
3643impl From < & KrateName > for KrateName {
3744 fn from ( krate_name : & KrateName ) -> Self {
@@ -44,7 +51,7 @@ impl FromStr for KrateName {
4451
4552 fn from_str ( s : & str ) -> Result < Self , Self :: Err > {
4653 validate_crate_name ( "crate" , s) ?;
47- Ok ( KrateName ( s. to_string ( ) ) )
54+ Ok ( KrateName ( Cow :: Owned ( s. to_string ( ) ) ) )
4855 }
4956}
5057
@@ -67,8 +74,21 @@ impl<'q> Encode<'q, Postgres> for KrateName {
6774
6875impl < ' r > Decode < ' r , Postgres > for KrateName {
6976 fn decode ( value : PgValueRef < ' r > ) -> Result < Self , BoxDynError > {
77+ // future improvement: we could also avoid the allocation here
78+ // and return a Cow::Borrowed while reading from the DB.
79+ // But this would mean the lifetime leaks into the whole codebase.
7080 let s: & str = Decode :: < Postgres > :: decode ( value) ?;
71- Ok ( Self ( s. parse ( ) ?) )
81+ Ok ( Self ( Cow :: Owned ( s. parse ( ) ?) ) )
82+ }
83+ }
84+
85+ impl PgHasArrayType for KrateName {
86+ fn array_type_info ( ) -> PgTypeInfo {
87+ <& str as PgHasArrayType >:: array_type_info ( )
88+ }
89+
90+ fn array_compatible ( ty : & PgTypeInfo ) -> bool {
91+ <& str as PgHasArrayType >:: array_compatible ( ty)
7292 }
7393}
7494
0 commit comments