@@ -872,11 +872,7 @@ impl LendingInstruction {
872
872
Self :: DonateToReserve { liquidity_amount }
873
873
}
874
874
25 => {
875
- let ( position_kind, rest) = match Self :: unpack_u8 ( rest) ? {
876
- ( 0 , rest) => ( PositionKind :: Deposit , rest) ,
877
- ( 1 , rest) => ( PositionKind :: Borrow , rest) ,
878
- _ => return Err ( LendingError :: InstructionUnpackError . into ( ) ) ,
879
- } ;
875
+ let ( position_kind, rest) = Self :: unpack_try_from_u8 ( rest) ?;
880
876
let ( start_time_secs, rest) = Self :: unpack_u64 ( rest) ?;
881
877
let ( end_time_secs, rest) = Self :: unpack_u64 ( rest) ?;
882
878
let ( token_amount, _rest) = Self :: unpack_u64 ( rest) ?;
@@ -888,23 +884,15 @@ impl LendingInstruction {
888
884
}
889
885
}
890
886
26 => {
891
- let ( position_kind, rest) = match Self :: unpack_u8 ( rest) ? {
892
- ( 0 , rest) => ( PositionKind :: Deposit , rest) ,
893
- ( 1 , rest) => ( PositionKind :: Borrow , rest) ,
894
- _ => return Err ( LendingError :: InstructionUnpackError . into ( ) ) ,
895
- } ;
887
+ let ( position_kind, rest) = Self :: unpack_try_from_u8 ( rest) ?;
896
888
let ( pool_reward_index, _rest) = Self :: unpack_u64 ( rest) ?;
897
889
Self :: ClosePoolReward {
898
890
position_kind,
899
891
pool_reward_index,
900
892
}
901
893
}
902
894
27 => {
903
- let ( position_kind, rest) = match Self :: unpack_u8 ( rest) ? {
904
- ( 0 , rest) => ( PositionKind :: Deposit , rest) ,
905
- ( 1 , rest) => ( PositionKind :: Borrow , rest) ,
906
- _ => return Err ( LendingError :: InstructionUnpackError . into ( ) ) ,
907
- } ;
895
+ let ( position_kind, rest) = Self :: unpack_try_from_u8 ( rest) ?;
908
896
let ( pool_reward_index, _rest) = Self :: unpack_u64 ( rest) ?;
909
897
Self :: CancelPoolReward {
910
898
position_kind,
@@ -960,6 +948,25 @@ impl LendingInstruction {
960
948
Ok ( ( value, rest) )
961
949
}
962
950
951
+ fn unpack_try_from_u8 < T > ( input : & [ u8 ] ) -> Result < ( T , & [ u8 ] ) , ProgramError >
952
+ where
953
+ T : TryFrom < u8 > ,
954
+ ProgramError : From < <T as TryFrom < u8 > >:: Error > ,
955
+ {
956
+ if input. is_empty ( ) {
957
+ msg ! ( "u8 cannot be unpacked" ) ;
958
+ return Err ( LendingError :: InstructionUnpackError . into ( ) ) ;
959
+ }
960
+ let ( bytes, rest) = input. split_at ( 1 ) ;
961
+ let value = bytes
962
+ . get ( ..1 )
963
+ . and_then ( |slice| slice. try_into ( ) . ok ( ) )
964
+ . map ( u8:: from_le_bytes)
965
+ . ok_or ( LendingError :: InstructionUnpackError ) ?;
966
+
967
+ Ok ( ( T :: try_from ( value) ?, rest) )
968
+ }
969
+
963
970
fn unpack_bytes32 ( input : & [ u8 ] ) -> Result < ( & [ u8 ; 32 ] , & [ u8 ] ) , ProgramError > {
964
971
if input. len ( ) < 32 {
965
972
msg ! ( "32 bytes cannot be unpacked" ) ;
0 commit comments