@@ -151,31 +151,42 @@ impl<'c> Translation<'c> {
151151 Ok ( WithStmts :: new_val ( val) )
152152 }
153153
154- CLiteral :: String ( ref val, width) => {
155- let mut val = val. to_owned ( ) ;
156- let num_elems = match self . ast_context . resolve_type ( ty. ctype ) . kind {
157- CTypeKind :: ConstantArray ( _elem_ty, num_elems) => num_elems,
158- ref kind => {
159- panic ! ( "String literal with unknown size: {val:?}, kind = {kind:?}" )
160- }
161- } ;
162-
163- // Match the literal size to the expected size padding with zeros as needed
164- let size = num_elems * ( width as usize ) ;
165- val. resize ( size, 0 ) ;
154+ CLiteral :: String ( ref bytes, element_size) => {
155+ let bytes_padded = self . string_literal_bytes ( ty. ctype , bytes, element_size) ;
166156
167157 // std::mem::transmute::<[u8; size], ctype>(*b"xxxx")
168- let u8_ty = mk ( ) . path_ty ( vec ! [ "u8" ] ) ;
169- let width_lit = mk ( ) . lit_expr ( mk ( ) . int_unsuffixed_lit ( val. len ( ) as u128 ) ) ;
170- Ok ( WithStmts :: new_unsafe_val ( transmute_expr (
171- mk ( ) . array_ty ( u8_ty, width_lit) ,
158+ let array_ty = mk ( ) . array_ty (
159+ mk ( ) . ident_ty ( "u8" ) ,
160+ mk ( ) . lit_expr ( bytes_padded. len ( ) as u128 ) ,
161+ ) ;
162+ let val = transmute_expr (
163+ array_ty,
172164 self . convert_type ( ty. ctype ) ?,
173- mk ( ) . unary_expr ( UnOp :: Deref ( Default :: default ( ) ) , mk ( ) . lit_expr ( val) ) ,
174- ) ) )
165+ mk ( ) . unary_expr ( UnOp :: Deref ( Default :: default ( ) ) , mk ( ) . lit_expr ( bytes_padded) ) ,
166+ ) ;
167+ Ok ( WithStmts :: new_unsafe_val ( val) )
175168 }
176169 }
177170 }
178171
172+ /// Returns the bytes of a string literal, including any additional zero bytes to pad the
173+ /// literal to the expected size.
174+ pub fn string_literal_bytes ( & self , ctype : CTypeId , bytes : & [ u8 ] , element_size : u8 ) -> Vec < u8 > {
175+ let num_elems = match self . ast_context . resolve_type ( ctype) . kind {
176+ CTypeKind :: ConstantArray ( _, num_elems) => num_elems,
177+ ref kind => {
178+ panic ! ( "String literal with unknown size: {bytes:?}, kind = {kind:?}" )
179+ }
180+ } ;
181+
182+ let size = num_elems * ( element_size as usize ) ;
183+ let mut bytes_padded = Vec :: with_capacity ( size) ;
184+ bytes_padded. extend ( bytes) ;
185+ bytes_padded. resize ( size, 0 ) ;
186+
187+ bytes_padded
188+ }
189+
179190 /// Convert an initialization list into an expression. These initialization lists can be
180191 /// used as array literals, struct literals, and union literals in code.
181192 pub fn convert_init_list (
0 commit comments