์ด ๊ธ์ด ์ ์๊ฒ ์ค์ง์ ์ผ๋ก ๋์์ด ๋์ต๋๋ค. ๊ฐ๋ ์ ์ผ๋ก ์ดํดํ๋ ๊ฒ๊ณผ ์์ด ๋๊ฐ๋ ๊ฒ์ ์กฐ๊ธ ๋ค๋ฅธ ๊ฐ๊ฐ์ธ ๊ฒ ๊ฐ๋ค์. ๋ง์น ์์ด์ ๋ ํด์ ํํ ๊ฐ์ด์.
์ฐธ๊ณ ํ์ฌ Span ํ์ฅ ํด๋์ค๋ฅผ ๋ง๋ค์ด ๋ดค์ต๋๋ค. ๊ฐ์ด ๋ณด์์ฃ .
public static class SpanExtension
{
public static ReadOnlySpan<byte> AsReadOnlyBytes<T>(this ref T @this)
where T : struct
{
var span = MemoryMarshal.CreateReadOnlySpan(ref @this, 1);
return MemoryMarshal.Cast<T, byte>(span);
}
public static ReadOnlySpan<byte> AsReadOnlyBytes<T>(this T[] @this)
where T : struct
{
return MemoryMarshal.Cast<T, byte>(@this);
}
public static Span<byte> AsBytes<T>(this ref T @this)
where T : struct
{
var span = MemoryMarshal.CreateSpan(ref @this, 1);
return MemoryMarshal.Cast<T, byte>(span);
}
public static Span<byte> AsBytes<T>(this T[] @this)
where T : struct
{
return MemoryMarshal.Cast<T, byte>(@this);
}
}
ํ์ฅ์ ๋ณด์๋ฉด MemoryMarshal์ ๊ธฐ๋ฅ์ ์ด์ฉํ ๊ฒ ๋ฟ์ด์ง๋ง, ๊ฐ๋ ฅํฉ๋๋ค. ์ด ํ์ฅ์ ์ด์ฉํด ๋ค์๊ณผ ๊ฐ์ด Stream์ ์ฐ๊ฑฐ๋ ์ฝ๋ ์ฝ๋๋ฅผ ๋จ์ํ ํ์์ต๋๋ค.
public void Write(Stream s)
{
s.Write(์ฒด๊ฒฐ์๊ฐ.AsReadOnlyBytes());
s.Write(์ฒด๊ฒฐ๊ฐ.AsReadOnlyBytes());
s.Write(์ฒด๊ฒฐ์๋.AsReadOnlyBytes());
s.Write(๋งค์ํธ๊ฐ์๋.AsReadOnlyBytes());
s.Write(๋งค๋ํธ๊ฐ์๋.AsReadOnlyBytes());
}
public static bool Read(Stream s, ref ์ค์๊ฐ์์ธ v)
{
var length = s.Read(v.์ฒด๊ฒฐ์๊ฐ.AsBytes());
if (length == 0)
return false;
s.Read(v.์ฒด๊ฒฐ๊ฐ.AsBytes());
s.Read(v.์ฒด๊ฒฐ์๋.AsBytes());
v.๋งค์ํธ๊ฐ์๋ = new decimal[5];
s.Read(v.๋งค์ํธ๊ฐ์๋.AsBytes());
v.๋งค๋ํธ๊ฐ์๋ = new decimal[5];
s.Read(v.๋งค๋ํธ๊ฐ์๋.AsBytes());
return true;
}
AsReadOnlyBytes()
๋ฅผ ํตํด ๋ฉ๋ชจ๋ฆฌ ํ ๋น ์์ด ํด๋น ํ๋๋ฅผ ReadOnlySpan๋ก ๋ณํํ์ฌ ์ฐ๊ธฐ๋ฅผ ํฉ๋๋ค.
๋์ฑ ์ฌ๋ฐ๋ ๊ฒ์ AsBytes()
๋ฅผ ํตํด ํด๋น ํ๋์ ๋ฉ๋ชจ๋ฆฌ ์์น๋ฅผ Span๋ก ๋ณํํ์ฌ ๋ฐ๋ก ์ฝ๊ธฐํ ์ ์๋ค๋ ๊ฒ์
๋๋ค.