1+ using System ;
2+ using System . Text ;
3+
4+ namespace BloomFilter ;
5+
6+ internal static class StringSpanExtensions
7+ {
8+ public static ReadOnlyMemory < byte > ToUtf8 ( this ReadOnlySpan < char > value )
9+ {
10+ #if NET6_0_OR_GREATER
11+ Memory < byte > bytes = new byte [ Encoding . UTF8 . GetByteCount ( value ) ] ;
12+ var bytesWritten = Encoding . UTF8 . GetBytes ( value , bytes . Span ) ;
13+ return bytes . Slice ( 0 , bytesWritten ) ;
14+
15+ #else
16+ var chars = value . ToArray ( ) ;
17+ var bytes = new byte [ Encoding . UTF8 . GetByteCount ( chars ) ] ;
18+ var bytesWritten = Encoding . UTF8 . GetBytes ( chars , 0 , value . Length , bytes , 0 ) ;
19+ return new ReadOnlyMemory < byte > ( bytes , 0 , bytesWritten ) ;
20+ #endif
21+ }
22+
23+ public static ReadOnlyMemory < char > FromUtf8 ( this ReadOnlySpan < byte > source )
24+ {
25+ #if NET6_0_OR_GREATER
26+ source = source . WithoutBom ( ) ;
27+ Memory < char > chars = new char [ Encoding . UTF8 . GetCharCount ( source ) ] ;
28+ var charsWritten = Encoding . UTF8 . GetChars ( source , chars . Span ) ;
29+ return chars . Slice ( 0 , charsWritten ) ;
30+ #else
31+ var bytes = source . WithoutBom ( ) . ToArray ( ) ;
32+ var chars = new char [ Encoding . UTF8 . GetCharCount ( bytes ) ] ;
33+ var charsWritten = Encoding . UTF8 . GetChars ( bytes , 0 , bytes . Length , chars , 0 ) ;
34+ return new ReadOnlyMemory < char > ( chars , 0 , charsWritten ) ;
35+
36+ #endif
37+ }
38+
39+ public static byte [ ] ToUtf8Bytes ( this ReadOnlySpan < char > value )
40+ {
41+ return ToUtf8 ( value ) . ToArray ( ) ;
42+ }
43+
44+ public static ReadOnlySpan < char > WithoutBom ( this ReadOnlySpan < char > value )
45+ {
46+ return value . Length > 0 && value [ 0 ] == 65279
47+ ? value . Slice ( 1 )
48+ : value ;
49+ }
50+
51+ public static ReadOnlySpan < byte > WithoutBom ( this ReadOnlySpan < byte > value )
52+ {
53+ return value . Length > 3 && value [ 0 ] == 0xEF && value [ 1 ] == 0xBB && value [ 2 ] == 0xBF
54+ ? value . Slice ( 3 )
55+ : value ;
56+ }
57+ }
0 commit comments