1+ namespace Hexa . NET . Utilities . Extensions
2+ {
3+ using System ;
4+ using System . Runtime . InteropServices ;
5+ using System . Text ;
6+
7+ public static unsafe class SpanHelper
8+ {
9+ public static ReadOnlySpan < char > CreateReadOnlySpanFromNullTerminated ( char * pointer )
10+ {
11+ int len = StrLen ( pointer ) ;
12+ return new ReadOnlySpan < char > ( pointer , len ) ;
13+ }
14+
15+ public static ReadOnlySpan < byte > CreateReadOnlySpanFromNullTerminated ( byte * pointer )
16+ {
17+ int len = StrLen ( pointer ) ;
18+ return new ReadOnlySpan < byte > ( pointer , len ) ;
19+ }
20+
21+ #if NETSTANDARD2_0
22+ public static bool StartsWith ( this ReadOnlySpan < char > span , char c )
23+ {
24+ return span . Length > 0 && span [ 0 ] == c ;
25+ }
26+
27+ public static bool StartsWith ( this string span , char c )
28+ {
29+ return span . Length > 0 && span [ 0 ] == c ;
30+ }
31+
32+ public static void Append ( this StringBuilder sb , ReadOnlySpan < char > span )
33+ {
34+ if ( span . IsEmpty )
35+ return ;
36+
37+ // Ensure the StringBuilder has enough capacity to avoid resizing during append
38+ sb . EnsureCapacity ( sb . Length + span . Length ) ;
39+
40+ // Manually append each character from the span to the StringBuilder
41+ foreach ( char c in span )
42+ {
43+ sb . Append ( c ) ;
44+ }
45+ }
46+
47+ public static int GetBytes ( this Encoding encoding , ReadOnlySpan < char > chars , Span < byte > bytes )
48+ {
49+ fixed ( char * pChars = chars )
50+ {
51+ fixed ( byte * pBytes = bytes )
52+ {
53+ return encoding . GetBytes ( pChars , chars . Length , pBytes , bytes . Length ) ;
54+ }
55+ }
56+ }
57+
58+ public static int GetChars ( this Encoding encoding , ReadOnlySpan < byte > bytes , Span < char > chars )
59+ {
60+ fixed ( byte * pBytes = bytes )
61+ {
62+ fixed ( char * pChars = chars )
63+ {
64+ return encoding . GetChars ( pBytes , bytes . Length , pChars , chars . Length ) ;
65+ }
66+ }
67+ }
68+
69+ public static int GetCharCount ( this Encoding encoding , ReadOnlySpan < byte > bytes )
70+ {
71+ fixed ( byte * pBytes = bytes )
72+ {
73+ return encoding . GetCharCount ( pBytes , bytes . Length ) ;
74+ }
75+ }
76+
77+ public static int GetByteCount ( this Encoding encoding , ReadOnlySpan < char > chars )
78+ {
79+ fixed ( char * pChars = chars )
80+ {
81+ return encoding . GetByteCount ( pChars , chars . Length ) ;
82+ }
83+ }
84+
85+ #endif
86+ }
87+
88+ public static unsafe class CollectionsExtensions
89+ {
90+ public static void AddRange < T > ( this IList < T > list , Span < T > values )
91+ {
92+ for ( int i = 0 ; i < values . Length ; i ++ )
93+ {
94+ list . Add ( values [ i ] ) ;
95+ }
96+ }
97+ }
98+ }
0 commit comments