1- // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
1+ // SPDX-FileCopyrightText: 2025 Demerzel Solutions Limited
22// SPDX-License-Identifier: LGPL-3.0-only
33
44using System ;
@@ -45,6 +45,7 @@ public static byte[] Slice(this byte[] bytes, int startIndex, int length)
4545 public static byte [ ] SliceWithZeroPaddingEmptyOnError ( this byte [ ] bytes , int startIndex , int length )
4646 {
4747 int copiedFragmentLength = Math . Min ( bytes . Length - startIndex , length ) ;
48+
4849 if ( copiedFragmentLength <= 0 )
4950 {
5051 return [ ] ;
@@ -59,21 +60,44 @@ public static byte[] SliceWithZeroPaddingEmptyOnError(this byte[] bytes, int sta
5960 public static ReadOnlySpan < byte > SliceWithZeroPaddingEmptyOnError ( this ReadOnlySpan < byte > bytes , int startIndex , int length )
6061 {
6162 int copiedFragmentLength = Math . Min ( bytes . Length - startIndex , length ) ;
63+
6264 if ( copiedFragmentLength <= 0 )
6365 {
6466 return default ;
6567 }
6668
69+ return SafeSliceWithZeroPadding ( bytes , startIndex , length , copiedFragmentLength ) ;
70+ }
71+
72+ public static ReadOnlySpan < byte > SliceWithZeroPaddingEmptyOnError ( this ReadOnlySpan < byte > bytes , uint startIndex , uint length )
73+ {
74+ if ( bytes . Length < startIndex )
75+ {
76+ return default ;
77+ }
78+
79+ long copiedFragmentLength = Math . Min ( ( uint ) bytes . Length - startIndex , length ) ;
80+
81+ if ( bytes . Length < startIndex + copiedFragmentLength )
82+ {
83+ return default ;
84+ }
85+
86+ return SafeSliceWithZeroPadding ( bytes , ( int ) startIndex , ( int ) length , ( int ) copiedFragmentLength ) ;
87+ }
88+
89+ private static ReadOnlySpan < byte > SafeSliceWithZeroPadding ( ReadOnlySpan < byte > bytes , int startIndex , int length , int copiedFragmentLength )
90+ {
6791 ReadOnlySpan < byte > sliced = bytes . Slice ( startIndex , copiedFragmentLength ) ;
92+
6893 if ( copiedFragmentLength < length )
6994 {
7095 byte [ ] extended = new byte [ length ] ;
7196 sliced . CopyTo ( extended ) ;
72- sliced = extended ;
97+ return extended ;
7398 }
7499
75100 return sliced ;
76101 }
77-
78102 }
79103}
0 commit comments