Span<T>, Memory<T> - slog(์™„๋ฃŒ)

์ด ๊ธ€์ด ์ €์—๊ฒ ์‹ค์งˆ์ ์œผ๋กœ ๋„์›€์ด ๋์Šต๋‹ˆ๋‹ค. ๊ฐœ๋…์ ์œผ๋กœ ์ดํ•ดํ•˜๋Š” ๊ฒƒ๊ณผ ์†์ด ๋‚˜๊ฐ€๋Š” ๊ฒƒ์€ ์กฐ๊ธˆ ๋‹ค๋ฅธ ๊ฐ๊ฐ์ธ ๊ฒƒ ๊ฐ™๋„ค์š”. ๋งˆ์น˜ ์˜์–ด์˜ ๋…ํ•ด์™€ ํšŒํ™” ๊ฐ™์ด์š”.

์ฐธ๊ณ ํ•˜์—ฌ 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๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐ”๋กœ ์ฝ๊ธฐํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

2 Likes