1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ---------------------------------------------------------------------------
// Native Format Reader
//
// UTF8 string reading methods
// ---------------------------------------------------------------------------
using System;
using System.Text;
namespace Internal.NativeFormat
{
internal partial struct NativeParser
{
public string GetString()
{
string value;
_offset = _reader.DecodeString(_offset, out value);
return value;
}
public void SkipString()
{
_offset = _reader.SkipString(_offset);
}
}
internal partial class NativeReader
{
public string ReadString(uint offset)
{
string value;
DecodeString(offset, out value);
return value;
}
public unsafe uint DecodeString(uint offset, out string value)
{
uint numBytes;
offset = DecodeUnsigned(offset, out numBytes);
if (numBytes == 0)
{
value = string.Empty;
return offset;
}
uint endOffset = offset + numBytes;
if (endOffset < numBytes || endOffset > _size)
ThrowBadImageFormatException();
#if NETFX_45
byte[] bytes = new byte[numBytes];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = *(_base + offset + i);
value = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
#else
value = Encoding.UTF8.GetString(_base + offset, (int)numBytes);
#endif
return endOffset;
}
// Decode a string, but just skip it instead of returning it
public uint SkipString(uint offset)
{
uint numBytes;
offset = DecodeUnsigned(offset, out numBytes);
if (numBytes == 0)
{
return offset;
}
uint endOffset = offset + numBytes;
if (endOffset < numBytes || endOffset > _size)
ThrowBadImageFormatException();
return endOffset;
}
public unsafe bool StringEquals(uint offset, string value)
{
uint originalOffset = offset;
uint numBytes;
offset = DecodeUnsigned(offset, out numBytes);
uint endOffset = offset + numBytes;
if (endOffset < numBytes || offset > _size)
ThrowBadImageFormatException();
if (numBytes < value.Length)
return false;
for (int i = 0; i < value.Length; i++)
{
int ch = *(_base + offset + i);
if (ch > 0x7F)
return ReadString(originalOffset) == value;
// We are assuming here that valid UTF8 encoded byte > 0x7F cannot map to a character with code point <= 0x7F
if (ch != value[i])
return false;
}
return numBytes == value.Length; // All char ANSI, all matching
}
}
}
|