Skip to content

Commit e4dd327

Browse files
committed
[增加]1. 增加ReadOnlySpan 的扩展函数
1 parent c6f0530 commit e4dd327

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

GameFrameX.Utility/Extensions/ReadOnlySpanExtension.cs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,4 +77,77 @@ public static long ReadLong(this ReadOnlySpan<byte> buffer, ref int offset)
7777
offset += ConstSize.LongSize;
7878
return value;
7979
}
80+
81+
/// <summary>
82+
/// 从字节数组中以指定偏移量读取无符号短整型。
83+
/// </summary>
84+
/// <param name="buffer">要从中读取数据的字节数组。</param>
85+
/// <param name="offset">读取数据的起始偏移量,此偏移量在读取后会自动增加。</param>
86+
/// <returns>读取的无符号短整型,若读取长度小于等于0或偏移量超出数组长度,返回0。</returns>
87+
public static ushort ReadUShort(this ReadOnlySpan<byte> buffer, ref int offset)
88+
{
89+
if (offset > buffer.Length + ConstSize.UShortSize)
90+
{
91+
throw new Exception("buffer read out of index");
92+
}
93+
94+
var value = BinaryPrimitives.ReadUInt16BigEndian(buffer[offset..]);
95+
offset += ConstSize.UShortSize;
96+
return value;
97+
}
98+
99+
/// <summary>
100+
/// 从字节数组中以指定偏移量读取短整型。
101+
/// </summary>
102+
/// <param name="buffer">要从中读取数据的字节数组。</param>
103+
/// <param name="offset">读取数据的起始偏移量,此偏移量在读取后会自动增加。</param>
104+
/// <returns>读取的短整型,若读取长度小于等于0或偏移量超出数组长度,返回0。</returns>
105+
public static short ReadShort(this ReadOnlySpan<byte> buffer, ref int offset)
106+
{
107+
if (offset > buffer.Length + ConstSize.ShortSize)
108+
{
109+
throw new Exception("buffer read out of index");
110+
}
111+
112+
var value = BinaryPrimitives.ReadInt16BigEndian(buffer[offset..]);
113+
offset += ConstSize.ShortSize;
114+
return value;
115+
}
116+
117+
/// <summary>
118+
/// 从字节数组中以指定偏移量读取单精度浮点数。
119+
/// </summary>
120+
/// <param name="buffer">要从中读取数据的字节数组。</param>
121+
/// <param name="offset">读取数据的起始偏移量,此偏移量在读取后会自动增加。</param>
122+
/// <returns>读取的单精度浮点数,若读取长度小于等于0或偏移量超出数组长度,返回0。</returns>
123+
public static float ReadFloat(this ReadOnlySpan<byte> buffer, ref int offset)
124+
{
125+
if (offset > buffer.Length + ConstSize.FloatSize)
126+
{
127+
throw new Exception("buffer read out of index");
128+
}
129+
130+
var value = BinaryPrimitives.ReadSingleBigEndian(buffer[offset..]);
131+
offset += ConstSize.FloatSize;
132+
return value;
133+
}
134+
135+
/// <summary>
136+
/// 从字节数组中以指定偏移量读取双精度浮点数。
137+
/// </summary>
138+
/// <param name="buffer">要从中读取数据的字节数组。</param>
139+
/// <param name="offset">读取数据的起始偏移量,此偏移量在读取后会自动增加。</param>
140+
/// <returns>读取的双精度浮点数,若读取长度小于等于0或偏移量超出数组长度,返回0。</returns>
141+
public static double ReadDouble(this ReadOnlySpan<byte> buffer, ref int offset)
142+
{
143+
if (offset > buffer.Length + ConstSize.DoubleSize)
144+
{
145+
throw new Exception("buffer read out of index");
146+
}
147+
148+
var value = BinaryPrimitives.ReadDoubleBigEndian(buffer[offset..]);
149+
offset += ConstSize.DoubleSize;
150+
return value;
151+
}
152+
80153
}

0 commit comments

Comments
 (0)