11// Copyright 2021 Contributors to the Parsec project.
22// SPDX-License-Identifier: Apache-2.0
3- use crate :: { tss2_esys:: UINT32 , Result } ;
3+ use crate :: { tss2_esys:: UINT32 , Error , Result , WrapperErrorKind } ;
4+ use log:: error;
45use std:: convert:: TryFrom ;
56
67/// Trait for types that can be converted into
@@ -25,6 +26,23 @@ pub trait Marshall: Sized {
2526 fn marshall_offset ( & self , _marshalled_data : & mut [ u8 ] , _offset : & mut usize ) -> Result < ( ) > {
2627 unimplemented ! ( ) ;
2728 }
29+
30+ /// Returns the type in form of marshalled data prefixed with their length
31+ fn marshall_prefixed ( & self ) -> Result < Vec < u8 > > {
32+ let data = self . marshall ( ) ?;
33+ let mut buffer = vec ! [ 0 ; data. len( ) + 2 ] ;
34+ buffer[ ..2 ] . copy_from_slice (
35+ & u16:: try_from ( data. len ( ) )
36+ . map_err ( |_| {
37+ error ! ( "object may only be 2^16 bytes long" ) ;
38+ Error :: local_error ( WrapperErrorKind :: WrongParamSize )
39+ } ) ?
40+ . to_be_bytes ( ) [ ..] ,
41+ ) ;
42+ buffer[ 2 ..] . copy_from_slice ( & data) ;
43+
44+ Ok ( buffer)
45+ }
2846}
2947
3048/// Trait for types that can be created from
@@ -186,3 +204,20 @@ pub(crate) use impl_mu_standard;
186204pub ( crate ) use impl_unmarshall_trait;
187205// Implementation of Marshall and UnMarshall macro for base TSS types.
188206impl_mu_aliases ! ( UINT32 ) ;
207+
208+ #[ cfg( feature = "rustcrypto" ) ]
209+ impl < T > Marshall for digest:: CtOutput < T >
210+ where
211+ T : digest:: OutputSizeUser ,
212+ {
213+ const BUFFER_SIZE : usize = <T :: OutputSize as digest:: typenum:: Unsigned >:: USIZE ;
214+
215+ fn marshall_offset ( & self , buf : & mut [ u8 ] , offset : & mut usize ) -> Result < ( ) > {
216+ let src = & self . as_bytes ( ) [ * offset..] ;
217+ let to_write = buf. len ( ) . min ( src. len ( ) ) ;
218+ buf[ ..to_write] . copy_from_slice ( & src[ ..to_write] ) ;
219+ * offset += to_write;
220+
221+ Ok ( ( ) )
222+ }
223+ }
0 commit comments