コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】文字列を Brotli で圧縮・展開するクラスの例

ソースコード

using System.IO;
using System.IO.Compression;
using System.Text;

namespace MyProject
{
    /// <summary>
    /// 文字列を Brotli で圧縮・展開するクラス
    /// </summary>
    public static class BrotliCompressor
    {
        //================================================================================
        // 変数(static readonly)
        //================================================================================
        private static readonly Encoding ENCODING = Encoding.UTF8;

        //================================================================================
        // 関数(static)
        //================================================================================
        /// <summary>
        /// 圧縮します
        /// </summary>
        public static byte[] Compress( string rawString )
        {
            var bytes = ENCODING.GetBytes( rawString );

            using var memoryStream = new MemoryStream();

            using ( var gZipStream = new BrotliStream( memoryStream, CompressionMode.Compress ) )
            {
                gZipStream.Write( bytes, 0, bytes.Length );
            }

            return memoryStream.ToArray();
        }

        /// <summary>
        /// 解凍します
        /// </summary>
        public static string Decompress( byte[] bytes )
        {
            using var memoryStream = new MemoryStream( bytes );
            using var gZipStream   = new BrotliStream( memoryStream, CompressionMode.Decompress );
            using var streamReader = new StreamReader( gZipStream, ENCODING );
            return streamReader.ReadToEnd();
        }
    }
}