1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387 |
- //------------------------------------------------------------
- // Game Framework
- // Copyright © 2013-2021 loyalsoft. All rights reserved.
- // Homepage: http://www.game7000.com/
- // Feedback: http://www.game7000.com/
- //------------------------------------------------------------
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Runtime.InteropServices;
- namespace GameFramework.FileSystem
- {
- /// <summary>
- /// 文件系统。
- /// </summary>
- internal sealed partial class FileSystem : IFileSystem
- {
- private const int ClusterSize = 1024 * 4;
- private const int CachedBytesLength = 0x1000;
- private static readonly string[] EmptyStringArray = new string[] { };
- private static readonly byte[] s_CachedBytes = new byte[CachedBytesLength];
- private static readonly int HeaderDataSize = Marshal.SizeOf(typeof(HeaderData));
- private static readonly int BlockDataSize = Marshal.SizeOf(typeof(BlockData));
- private static readonly int StringDataSize = Marshal.SizeOf(typeof(StringData));
- private readonly string m_FullPath;
- private readonly FileSystemAccess m_Access;
- private readonly FileSystemStream m_Stream;
- private readonly Dictionary<string, int> m_FileDatas;
- private readonly List<BlockData> m_BlockDatas;
- private readonly GameFrameworkMultiDictionary<int, int> m_FreeBlockIndexes;
- private readonly SortedDictionary<int, StringData> m_StringDatas;
- private readonly Queue<KeyValuePair<int, StringData>> m_FreeStringDatas;
- private HeaderData m_HeaderData;
- private int m_BlockDataOffset;
- private int m_StringDataOffset;
- private int m_FileDataOffset;
- /// <summary>
- /// 初始化文件系统的新实例。
- /// </summary>
- /// <param name="fullPath">文件系统完整路径。</param>
- /// <param name="access">文件系统访问方式。</param>
- /// <param name="stream">文件系统流。</param>
- private FileSystem(string fullPath, FileSystemAccess access, FileSystemStream stream)
- {
- if (string.IsNullOrEmpty(fullPath))
- {
- throw new GameFrameworkException("Full path is invalid.");
- }
- if (access == FileSystemAccess.Unspecified)
- {
- throw new GameFrameworkException("Access is invalid.");
- }
- if (stream == null)
- {
- throw new GameFrameworkException("Stream is invalid.");
- }
- m_FullPath = fullPath;
- m_Access = access;
- m_Stream = stream;
- m_FileDatas = new Dictionary<string, int>(StringComparer.Ordinal);
- m_BlockDatas = new List<BlockData>();
- m_FreeBlockIndexes = new GameFrameworkMultiDictionary<int, int>();
- m_StringDatas = new SortedDictionary<int, StringData>();
- m_FreeStringDatas = new Queue<KeyValuePair<int, StringData>>();
- m_HeaderData = default(HeaderData);
- m_BlockDataOffset = 0;
- m_StringDataOffset = 0;
- m_FileDataOffset = 0;
- Utility.Marshal.EnsureCachedHGlobalSize(CachedBytesLength);
- }
- /// <summary>
- /// 获取文件系统完整路径。
- /// </summary>
- public string FullPath
- {
- get
- {
- return m_FullPath;
- }
- }
- /// <summary>
- /// 获取文件系统访问方式。
- /// </summary>
- public FileSystemAccess Access
- {
- get
- {
- return m_Access;
- }
- }
- /// <summary>
- /// 获取文件数量。
- /// </summary>
- public int FileCount
- {
- get
- {
- return m_FileDatas.Count;
- }
- }
- /// <summary>
- /// 获取最大文件数量。
- /// </summary>
- public int MaxFileCount
- {
- get
- {
- return m_HeaderData.MaxFileCount;
- }
- }
- /// <summary>
- /// 创建文件系统。
- /// </summary>
- /// <param name="fullPath">要创建的文件系统的完整路径。</param>
- /// <param name="access">要创建的文件系统的访问方式。</param>
- /// <param name="stream">要创建的文件系统的文件系统流。</param>
- /// <param name="maxFileCount">要创建的文件系统的最大文件数量。</param>
- /// <param name="maxBlockCount">要创建的文件系统的最大块数据数量。</param>
- /// <returns>创建的文件系统。</returns>
- public static FileSystem Create(string fullPath, FileSystemAccess access, FileSystemStream stream, int maxFileCount, int maxBlockCount)
- {
- if (maxFileCount <= 0)
- {
- throw new GameFrameworkException("Max file count is invalid.");
- }
- if (maxBlockCount <= 0)
- {
- throw new GameFrameworkException("Max block count is invalid.");
- }
- if (maxFileCount > maxBlockCount)
- {
- throw new GameFrameworkException("Max file count can not larger than max block count.");
- }
- FileSystem fileSystem = new FileSystem(fullPath, access, stream);
- fileSystem.m_HeaderData = new HeaderData(maxFileCount, maxBlockCount);
- CalcOffsets(fileSystem);
- Utility.Marshal.StructureToBytes(fileSystem.m_HeaderData, HeaderDataSize, s_CachedBytes);
- try
- {
- stream.Write(s_CachedBytes, 0, HeaderDataSize);
- stream.SetLength(fileSystem.m_FileDataOffset);
- return fileSystem;
- }
- catch
- {
- fileSystem.Shutdown();
- return null;
- }
- }
- /// <summary>
- /// 加载文件系统。
- /// </summary>
- /// <param name="fullPath">要加载的文件系统的完整路径。</param>
- /// <param name="access">要加载的文件系统的访问方式。</param>
- /// <param name="stream">要加载的文件系统的文件系统流。</param>
- /// <returns>加载的文件系统。</returns>
- public static FileSystem Load(string fullPath, FileSystemAccess access, FileSystemStream stream)
- {
- FileSystem fileSystem = new FileSystem(fullPath, access, stream);
- stream.Read(s_CachedBytes, 0, HeaderDataSize);
- fileSystem.m_HeaderData = Utility.Marshal.BytesToStructure<HeaderData>(HeaderDataSize, s_CachedBytes);
- if (!fileSystem.m_HeaderData.IsValid)
- {
- throw new GameFrameworkException(Utility.Text.Format("File system '{0}' is invalid.", fullPath));
- }
- CalcOffsets(fileSystem);
- if (fileSystem.m_BlockDatas.Capacity < fileSystem.m_HeaderData.BlockCount)
- {
- fileSystem.m_BlockDatas.Capacity = fileSystem.m_HeaderData.BlockCount;
- }
- for (int i = 0; i < fileSystem.m_HeaderData.BlockCount; i++)
- {
- stream.Read(s_CachedBytes, 0, BlockDataSize);
- BlockData blockData = Utility.Marshal.BytesToStructure<BlockData>(BlockDataSize, s_CachedBytes);
- fileSystem.m_BlockDatas.Add(blockData);
- }
- for (int i = 0; i < fileSystem.m_BlockDatas.Count; i++)
- {
- BlockData blockData = fileSystem.m_BlockDatas[i];
- if (blockData.Using)
- {
- StringData stringData = fileSystem.ReadStringData(blockData.StringIndex);
- fileSystem.m_StringDatas.Add(blockData.StringIndex, stringData);
- fileSystem.m_FileDatas.Add(stringData.GetString(fileSystem.m_HeaderData.GetEncryptBytes()), i);
- }
- else
- {
- fileSystem.m_FreeBlockIndexes.Add(blockData.Length, i);
- }
- }
- return fileSystem;
- }
- /// <summary>
- /// 关闭并清理文件系统。
- /// </summary>
- public void Shutdown()
- {
- m_Stream.Close();
- m_FileDatas.Clear();
- m_BlockDatas.Clear();
- m_FreeBlockIndexes.Clear();
- m_StringDatas.Clear();
- m_FreeStringDatas.Clear();
- m_BlockDataOffset = 0;
- m_StringDataOffset = 0;
- m_FileDataOffset = 0;
- }
- /// <summary>
- /// 获取文件信息。
- /// </summary>
- /// <param name="name">要获取文件信息的文件名称。</param>
- /// <returns>获取的文件信息。</returns>
- public FileInfo GetFileInfo(string name)
- {
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- int blockIndex = 0;
- if (!m_FileDatas.TryGetValue(name, out blockIndex))
- {
- return default(FileInfo);
- }
- BlockData blockData = m_BlockDatas[blockIndex];
- return new FileInfo(name, GetClusterOffset(blockData.ClusterIndex), blockData.Length);
- }
- /// <summary>
- /// 获取所有文件信息。
- /// </summary>
- /// <returns>获取的所有文件信息。</returns>
- public FileInfo[] GetAllFileInfos()
- {
- int index = 0;
- FileInfo[] results = new FileInfo[m_FileDatas.Count];
- foreach (KeyValuePair<string, int> fileData in m_FileDatas)
- {
- BlockData blockData = m_BlockDatas[fileData.Value];
- results[index++] = new FileInfo(fileData.Key, GetClusterOffset(blockData.ClusterIndex), blockData.Length);
- }
- return results;
- }
- /// <summary>
- /// 获取所有文件信息。
- /// </summary>
- /// <param name="results">获取的所有文件信息。</param>
- public void GetAllFileInfos(List<FileInfo> results)
- {
- if (results == null)
- {
- throw new GameFrameworkException("Results is invalid.");
- }
- results.Clear();
- foreach (KeyValuePair<string, int> fileData in m_FileDatas)
- {
- BlockData blockData = m_BlockDatas[fileData.Value];
- results.Add(new FileInfo(fileData.Key, GetClusterOffset(blockData.ClusterIndex), blockData.Length));
- }
- }
- /// <summary>
- /// 检查是否存在指定文件。
- /// </summary>
- /// <param name="name">要检查的文件名称。</param>
- /// <returns>是否存在指定文件。</returns>
- public bool HasFile(string name)
- {
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- return m_FileDatas.ContainsKey(name);
- }
- /// <summary>
- /// 读取指定文件。
- /// </summary>
- /// <param name="name">要读取的文件名称。</param>
- /// <returns>存储读取文件内容的二进制流。</returns>
- public byte[] ReadFile(string name)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return null;
- }
- int length = fileInfo.Length;
- byte[] buffer = new byte[length];
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset;
- m_Stream.Read(buffer, 0, length);
- }
- return buffer;
- }
- /// <summary>
- /// 读取指定文件。
- /// </summary>
- /// <param name="name">要读取的文件名称。</param>
- /// <param name="buffer">存储读取文件内容的二进制流。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFile(string name, byte[] buffer)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return ReadFile(name, buffer, 0, buffer.Length);
- }
- /// <summary>
- /// 读取指定文件。
- /// </summary>
- /// <param name="name">要读取的文件名称。</param>
- /// <param name="buffer">存储读取文件内容的二进制流。</param>
- /// <param name="startIndex">存储读取文件内容的二进制流的起始位置。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFile(string name, byte[] buffer, int startIndex)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return ReadFile(name, buffer, startIndex, buffer.Length - startIndex);
- }
- /// <summary>
- /// 读取指定文件。
- /// </summary>
- /// <param name="name">要读取的文件名称。</param>
- /// <param name="buffer">存储读取文件内容的二进制流。</param>
- /// <param name="startIndex">存储读取文件内容的二进制流的起始位置。</param>
- /// <param name="length">存储读取文件内容的二进制流的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFile(string name, byte[] buffer, int startIndex, int length)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
- {
- throw new GameFrameworkException("Start index or length is invalid.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return 0;
- }
- m_Stream.Position = fileInfo.Offset;
- if (length > fileInfo.Length)
- {
- length = fileInfo.Length;
- }
- if (length > 0)
- {
- return m_Stream.Read(buffer, startIndex, length);
- }
- return 0;
- }
- /// <summary>
- /// 读取指定文件。
- /// </summary>
- /// <param name="name">要读取的文件名称。</param>
- /// <param name="stream">存储读取文件内容的二进制流。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFile(string name, Stream stream)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (stream == null)
- {
- throw new GameFrameworkException("Stream is invalid.");
- }
- if (!stream.CanWrite)
- {
- throw new GameFrameworkException("Stream is not writable.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return 0;
- }
- int length = fileInfo.Length;
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset;
- return m_Stream.Read(stream, length);
- }
- return 0;
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>存储读取文件片段内容的二进制流。</returns>
- public byte[] ReadFileSegment(string name, int length)
- {
- return ReadFileSegment(name, 0, length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="offset">要读取片段的偏移。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>存储读取文件片段内容的二进制流。</returns>
- public byte[] ReadFileSegment(string name, int offset, int length)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (offset < 0)
- {
- throw new GameFrameworkException("Index is invalid.");
- }
- if (length < 0)
- {
- throw new GameFrameworkException("Length is invalid.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return null;
- }
- if (offset > fileInfo.Length)
- {
- offset = fileInfo.Length;
- }
- int leftLength = fileInfo.Length - offset;
- if (length > leftLength)
- {
- length = leftLength;
- }
- byte[] buffer = new byte[length];
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset + offset;
- m_Stream.Read(buffer, 0, length);
- }
- return buffer;
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, byte[] buffer)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return ReadFileSegment(name, 0, buffer, 0, buffer.Length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, byte[] buffer, int length)
- {
- return ReadFileSegment(name, 0, buffer, 0, length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <param name="startIndex">存储读取文件片段内容的二进制流的起始位置。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, byte[] buffer, int startIndex, int length)
- {
- return ReadFileSegment(name, 0, buffer, startIndex, length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="offset">要读取片段的偏移。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, int offset, byte[] buffer)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return ReadFileSegment(name, offset, buffer, 0, buffer.Length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="offset">要读取片段的偏移。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, int offset, byte[] buffer, int length)
- {
- return ReadFileSegment(name, offset, buffer, 0, length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="offset">要读取片段的偏移。</param>
- /// <param name="buffer">存储读取文件片段内容的二进制流。</param>
- /// <param name="startIndex">存储读取文件片段内容的二进制流的起始位置。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, int offset, byte[] buffer, int startIndex, int length)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (offset < 0)
- {
- throw new GameFrameworkException("Index is invalid.");
- }
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
- {
- throw new GameFrameworkException("Start index or length is invalid.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return 0;
- }
- if (offset > fileInfo.Length)
- {
- offset = fileInfo.Length;
- }
- int leftLength = fileInfo.Length - offset;
- if (length > leftLength)
- {
- length = leftLength;
- }
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset + offset;
- return m_Stream.Read(buffer, startIndex, length);
- }
- return 0;
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="stream">存储读取文件片段内容的二进制流。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, Stream stream, int length)
- {
- return ReadFileSegment(name, 0, stream, length);
- }
- /// <summary>
- /// 读取指定文件的指定片段。
- /// </summary>
- /// <param name="name">要读取片段的文件名称。</param>
- /// <param name="offset">要读取片段的偏移。</param>
- /// <param name="stream">存储读取文件片段内容的二进制流。</param>
- /// <param name="length">要读取片段的长度。</param>
- /// <returns>实际读取了多少字节。</returns>
- public int ReadFileSegment(string name, int offset, Stream stream, int length)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (offset < 0)
- {
- throw new GameFrameworkException("Index is invalid.");
- }
- if (stream == null)
- {
- throw new GameFrameworkException("Stream is invalid.");
- }
- if (!stream.CanWrite)
- {
- throw new GameFrameworkException("Stream is not writable.");
- }
- if (length < 0)
- {
- throw new GameFrameworkException("Length is invalid.");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return 0;
- }
- if (offset > fileInfo.Length)
- {
- offset = fileInfo.Length;
- }
- int leftLength = fileInfo.Length - offset;
- if (length > leftLength)
- {
- length = leftLength;
- }
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset + offset;
- return m_Stream.Read(stream, length);
- }
- return 0;
- }
- /// <summary>
- /// 写入指定文件。
- /// </summary>
- /// <param name="name">要写入的文件名称。</param>
- /// <param name="buffer">存储写入文件内容的二进制流。</param>
- /// <returns>是否写入指定文件成功。</returns>
- public bool WriteFile(string name, byte[] buffer)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return WriteFile(name, buffer, 0, buffer.Length);
- }
- /// <summary>
- /// 写入指定文件。
- /// </summary>
- /// <param name="name">要写入的文件名称。</param>
- /// <param name="buffer">存储写入文件内容的二进制流。</param>
- /// <param name="startIndex">存储写入文件内容的二进制流的起始位置。</param>
- /// <returns>是否写入指定文件成功。</returns>
- public bool WriteFile(string name, byte[] buffer, int startIndex)
- {
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- return WriteFile(name, buffer, startIndex, buffer.Length - startIndex);
- }
- /// <summary>
- /// 写入指定文件。
- /// </summary>
- /// <param name="name">要写入的文件名称。</param>
- /// <param name="buffer">存储写入文件内容的二进制流。</param>
- /// <param name="startIndex">存储写入文件内容的二进制流的起始位置。</param>
- /// <param name="length">存储写入文件内容的二进制流的长度。</param>
- /// <returns>是否写入指定文件成功。</returns>
- public bool WriteFile(string name, byte[] buffer, int startIndex, int length)
- {
- if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not writable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (name.Length > byte.MaxValue)
- {
- throw new GameFrameworkException(Utility.Text.Format("Name '{0}' is too long.", name));
- }
- if (buffer == null)
- {
- throw new GameFrameworkException("Buffer is invalid.");
- }
- if (startIndex < 0 || length < 0 || startIndex + length > buffer.Length)
- {
- throw new GameFrameworkException("Start index or length is invalid.");
- }
- bool hasFile = false;
- int oldBlockIndex = -1;
- if (m_FileDatas.TryGetValue(name, out oldBlockIndex))
- {
- hasFile = true;
- }
- if (!hasFile && m_FileDatas.Count >= m_HeaderData.MaxFileCount)
- {
- return false;
- }
- int blockIndex = AllocBlock(length);
- if (blockIndex < 0)
- {
- return false;
- }
- if (length > 0)
- {
- m_Stream.Position = GetClusterOffset(m_BlockDatas[blockIndex].ClusterIndex);
- m_Stream.Write(buffer, startIndex, length);
- }
- ProcessWriteFile(name, hasFile, oldBlockIndex, blockIndex, length);
- m_Stream.Flush();
- return true;
- }
- /// <summary>
- /// 写入指定文件。
- /// </summary>
- /// <param name="name">要写入的文件名称。</param>
- /// <param name="stream">存储写入文件内容的二进制流。</param>
- /// <returns>是否写入指定文件成功。</returns>
- public bool WriteFile(string name, Stream stream)
- {
- if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not writable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (name.Length > byte.MaxValue)
- {
- throw new GameFrameworkException(Utility.Text.Format("Name '{0}' is too long.", name));
- }
- if (stream == null)
- {
- throw new GameFrameworkException("Stream is invalid.");
- }
- if (!stream.CanRead)
- {
- throw new GameFrameworkException("Stream is not readable.");
- }
- bool hasFile = false;
- int oldBlockIndex = -1;
- if (m_FileDatas.TryGetValue(name, out oldBlockIndex))
- {
- hasFile = true;
- }
- if (!hasFile && m_FileDatas.Count >= m_HeaderData.MaxFileCount)
- {
- return false;
- }
- int length = (int)(stream.Length - stream.Position);
- int blockIndex = AllocBlock(length);
- if (blockIndex < 0)
- {
- return false;
- }
- if (length > 0)
- {
- m_Stream.Position = GetClusterOffset(m_BlockDatas[blockIndex].ClusterIndex);
- m_Stream.Write(stream, length);
- }
- ProcessWriteFile(name, hasFile, oldBlockIndex, blockIndex, length);
- m_Stream.Flush();
- return true;
- }
- /// <summary>
- /// 写入指定文件。
- /// </summary>
- /// <param name="name">要写入的文件名称。</param>
- /// <param name="filePath">存储写入文件内容的文件路径。</param>
- /// <returns>是否写入指定文件成功。</returns>
- public bool WriteFile(string name, string filePath)
- {
- if (string.IsNullOrEmpty(filePath))
- {
- throw new GameFrameworkException("File path is invalid");
- }
- if (!File.Exists(filePath))
- {
- return false;
- }
- using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- return WriteFile(name, fileStream);
- }
- }
- /// <summary>
- /// 将指定文件另存为物理文件。
- /// </summary>
- /// <param name="name">要另存为的文件名称。</param>
- /// <param name="filePath">存储写入文件内容的文件路径。</param>
- /// <returns>是否将指定文件另存为物理文件成功。</returns>
- public bool SaveAsFile(string name, string filePath)
- {
- if (m_Access != FileSystemAccess.Read && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not readable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- if (string.IsNullOrEmpty(filePath))
- {
- throw new GameFrameworkException("File path is invalid");
- }
- FileInfo fileInfo = GetFileInfo(name);
- if (!fileInfo.IsValid)
- {
- return false;
- }
- try
- {
- if (File.Exists(filePath))
- {
- File.Delete(filePath);
- }
- string directory = Path.GetDirectoryName(filePath);
- if (!Directory.Exists(directory))
- {
- Directory.CreateDirectory(directory);
- }
- using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
- {
- int length = fileInfo.Length;
- if (length > 0)
- {
- m_Stream.Position = fileInfo.Offset;
- return m_Stream.Read(fileStream, length) == length;
- }
- return true;
- }
- }
- catch
- {
- return false;
- }
- }
- /// <summary>
- /// 重命名指定文件。
- /// </summary>
- /// <param name="oldName">要重命名的文件名称。</param>
- /// <param name="newName">重命名后的文件名称。</param>
- /// <returns>是否重命名指定文件成功。</returns>
- public bool RenameFile(string oldName, string newName)
- {
- if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not writable.");
- }
- if (string.IsNullOrEmpty(oldName))
- {
- throw new GameFrameworkException("Old name is invalid.");
- }
- if (string.IsNullOrEmpty(newName))
- {
- throw new GameFrameworkException("New name is invalid.");
- }
- if (newName.Length > byte.MaxValue)
- {
- throw new GameFrameworkException(Utility.Text.Format("New name '{0}' is too long.", newName));
- }
- if (oldName == newName)
- {
- return true;
- }
- if (m_FileDatas.ContainsKey(newName))
- {
- return false;
- }
- int blockIndex = 0;
- if (!m_FileDatas.TryGetValue(oldName, out blockIndex))
- {
- return false;
- }
- int stringIndex = m_BlockDatas[blockIndex].StringIndex;
- StringData stringData = m_StringDatas[stringIndex].SetString(newName, m_HeaderData.GetEncryptBytes());
- m_StringDatas[stringIndex] = stringData;
- WriteStringData(stringIndex, stringData);
- m_FileDatas.Add(newName, blockIndex);
- m_FileDatas.Remove(oldName);
- m_Stream.Flush();
- return true;
- }
- /// <summary>
- /// 删除指定文件。
- /// </summary>
- /// <param name="name">要删除的文件名称。</param>
- /// <returns>是否删除指定文件成功。</returns>
- public bool DeleteFile(string name)
- {
- if (m_Access != FileSystemAccess.Write && m_Access != FileSystemAccess.ReadWrite)
- {
- throw new GameFrameworkException("File system is not writable.");
- }
- if (string.IsNullOrEmpty(name))
- {
- throw new GameFrameworkException("Name is invalid.");
- }
- int blockIndex = 0;
- if (!m_FileDatas.TryGetValue(name, out blockIndex))
- {
- return false;
- }
- m_FileDatas.Remove(name);
- BlockData blockData = m_BlockDatas[blockIndex];
- int stringIndex = blockData.StringIndex;
- StringData stringData = m_StringDatas[stringIndex].Clear();
- m_FreeStringDatas.Enqueue(new KeyValuePair<int, StringData>(stringIndex, stringData));
- m_StringDatas.Remove(stringIndex);
- WriteStringData(stringIndex, stringData);
- blockData = blockData.Free();
- m_BlockDatas[blockIndex] = blockData;
- if (!TryCombineFreeBlocks(blockIndex))
- {
- m_FreeBlockIndexes.Add(blockData.Length, blockIndex);
- WriteBlockData(blockIndex);
- }
- m_Stream.Flush();
- return true;
- }
- private void ProcessWriteFile(string name, bool hasFile, int oldBlockIndex, int blockIndex, int length)
- {
- BlockData blockData = m_BlockDatas[blockIndex];
- if (hasFile)
- {
- BlockData oldBlockData = m_BlockDatas[oldBlockIndex];
- blockData = new BlockData(oldBlockData.StringIndex, blockData.ClusterIndex, length);
- m_BlockDatas[blockIndex] = blockData;
- WriteBlockData(blockIndex);
- oldBlockData = oldBlockData.Free();
- m_BlockDatas[oldBlockIndex] = oldBlockData;
- if (!TryCombineFreeBlocks(oldBlockIndex))
- {
- m_FreeBlockIndexes.Add(oldBlockData.Length, oldBlockIndex);
- WriteBlockData(oldBlockIndex);
- }
- }
- else
- {
- int stringIndex = AllocString(name);
- blockData = new BlockData(stringIndex, blockData.ClusterIndex, length);
- m_BlockDatas[blockIndex] = blockData;
- WriteBlockData(blockIndex);
- }
- if (hasFile)
- {
- m_FileDatas[name] = blockIndex;
- }
- else
- {
- m_FileDatas.Add(name, blockIndex);
- }
- }
- private bool TryCombineFreeBlocks(int freeBlockIndex)
- {
- BlockData freeBlockData = m_BlockDatas[freeBlockIndex];
- if (freeBlockData.Length <= 0)
- {
- return false;
- }
- int previousFreeBlockIndex = -1;
- int nextFreeBlockIndex = -1;
- int nextBlockDataClusterIndex = freeBlockData.ClusterIndex + GetUpBoundClusterCount(freeBlockData.Length);
- foreach (KeyValuePair<int, GameFrameworkLinkedListRange<int>> blockIndexes in m_FreeBlockIndexes)
- {
- if (blockIndexes.Key <= 0)
- {
- continue;
- }
- int blockDataClusterCount = GetUpBoundClusterCount(blockIndexes.Key);
- foreach (int blockIndex in blockIndexes.Value)
- {
- BlockData blockData = m_BlockDatas[blockIndex];
- if (blockData.ClusterIndex + blockDataClusterCount == freeBlockData.ClusterIndex)
- {
- previousFreeBlockIndex = blockIndex;
- }
- else if (blockData.ClusterIndex == nextBlockDataClusterIndex)
- {
- nextFreeBlockIndex = blockIndex;
- }
- }
- }
- if (previousFreeBlockIndex < 0 && nextFreeBlockIndex < 0)
- {
- return false;
- }
- m_FreeBlockIndexes.Remove(freeBlockData.Length, freeBlockIndex);
- if (previousFreeBlockIndex >= 0)
- {
- BlockData previousFreeBlockData = m_BlockDatas[previousFreeBlockIndex];
- m_FreeBlockIndexes.Remove(previousFreeBlockData.Length, previousFreeBlockIndex);
- freeBlockData = new BlockData(previousFreeBlockData.ClusterIndex, previousFreeBlockData.Length + freeBlockData.Length);
- m_BlockDatas[previousFreeBlockIndex] = BlockData.Empty;
- m_FreeBlockIndexes.Add(0, previousFreeBlockIndex);
- WriteBlockData(previousFreeBlockIndex);
- }
- if (nextFreeBlockIndex >= 0)
- {
- BlockData nextFreeBlockData = m_BlockDatas[nextFreeBlockIndex];
- m_FreeBlockIndexes.Remove(nextFreeBlockData.Length, nextFreeBlockIndex);
- freeBlockData = new BlockData(freeBlockData.ClusterIndex, freeBlockData.Length + nextFreeBlockData.Length);
- m_BlockDatas[nextFreeBlockIndex] = BlockData.Empty;
- m_FreeBlockIndexes.Add(0, nextFreeBlockIndex);
- WriteBlockData(nextFreeBlockIndex);
- }
- m_BlockDatas[freeBlockIndex] = freeBlockData;
- m_FreeBlockIndexes.Add(freeBlockData.Length, freeBlockIndex);
- WriteBlockData(freeBlockIndex);
- return true;
- }
- private int GetEmptyBlockIndex()
- {
- GameFrameworkLinkedListRange<int> lengthRange = default(GameFrameworkLinkedListRange<int>);
- if (m_FreeBlockIndexes.TryGetValue(0, out lengthRange))
- {
- int blockIndex = lengthRange.First.Value;
- m_FreeBlockIndexes.Remove(0, blockIndex);
- return blockIndex;
- }
- if (m_BlockDatas.Count < m_HeaderData.MaxBlockCount)
- {
- int blockIndex = m_BlockDatas.Count;
- m_BlockDatas.Add(BlockData.Empty);
- WriteHeaderData();
- return blockIndex;
- }
- return -1;
- }
- private int AllocBlock(int length)
- {
- if (length <= 0)
- {
- return GetEmptyBlockIndex();
- }
- length = (int)GetUpBoundClusterOffset(length);
- int lengthFound = -1;
- GameFrameworkLinkedListRange<int> lengthRange = default(GameFrameworkLinkedListRange<int>);
- foreach (KeyValuePair<int, GameFrameworkLinkedListRange<int>> i in m_FreeBlockIndexes)
- {
- if (i.Key < length)
- {
- continue;
- }
- if (lengthFound >= 0 && lengthFound < i.Key)
- {
- continue;
- }
- lengthFound = i.Key;
- lengthRange = i.Value;
- }
- if (lengthFound >= 0)
- {
- if (lengthFound > length && m_BlockDatas.Count >= m_HeaderData.MaxBlockCount)
- {
- return -1;
- }
- int blockIndex = lengthRange.First.Value;
- m_FreeBlockIndexes.Remove(lengthFound, blockIndex);
- if (lengthFound > length)
- {
- BlockData blockData = m_BlockDatas[blockIndex];
- m_BlockDatas[blockIndex] = new BlockData(blockData.ClusterIndex, length);
- WriteBlockData(blockIndex);
- int deltaLength = lengthFound - length;
- int anotherBlockIndex = GetEmptyBlockIndex();
- m_BlockDatas[anotherBlockIndex] = new BlockData(blockData.ClusterIndex + GetUpBoundClusterCount(length), deltaLength);
- m_FreeBlockIndexes.Add(deltaLength, anotherBlockIndex);
- WriteBlockData(anotherBlockIndex);
- }
- return blockIndex;
- }
- else
- {
- int blockIndex = GetEmptyBlockIndex();
- if (blockIndex < 0)
- {
- return -1;
- }
- long fileLength = m_Stream.Length;
- try
- {
- m_Stream.SetLength(fileLength + length);
- }
- catch
- {
- return -1;
- }
- m_BlockDatas[blockIndex] = new BlockData(GetUpBoundClusterCount(fileLength), length);
- WriteBlockData(blockIndex);
- return blockIndex;
- }
- }
- private int AllocString(string value)
- {
- int stringIndex = -1;
- StringData stringData = default(StringData);
- if (m_FreeStringDatas.Count > 0)
- {
- KeyValuePair<int, StringData> freeStringData = m_FreeStringDatas.Dequeue();
- stringIndex = freeStringData.Key;
- stringData = freeStringData.Value;
- }
- else
- {
- int index = 0;
- foreach (KeyValuePair<int, StringData> i in m_StringDatas)
- {
- if (i.Key == index)
- {
- index++;
- continue;
- }
- break;
- }
- if (index < m_HeaderData.MaxFileCount)
- {
- stringIndex = index;
- byte[] bytes = new byte[byte.MaxValue];
- Utility.Random.GetRandomBytes(bytes);
- stringData = new StringData(0, bytes);
- }
- }
- if (stringIndex < 0)
- {
- throw new GameFrameworkException("Alloc string internal error.");
- }
- stringData = stringData.SetString(value, m_HeaderData.GetEncryptBytes());
- m_StringDatas.Add(stringIndex, stringData);
- WriteStringData(stringIndex, stringData);
- return stringIndex;
- }
- private void WriteHeaderData()
- {
- m_HeaderData = m_HeaderData.SetBlockCount(m_BlockDatas.Count);
- Utility.Marshal.StructureToBytes(m_HeaderData, HeaderDataSize, s_CachedBytes);
- m_Stream.Position = 0L;
- m_Stream.Write(s_CachedBytes, 0, HeaderDataSize);
- }
- private void WriteBlockData(int blockIndex)
- {
- Utility.Marshal.StructureToBytes(m_BlockDatas[blockIndex], BlockDataSize, s_CachedBytes);
- m_Stream.Position = m_BlockDataOffset + BlockDataSize * blockIndex;
- m_Stream.Write(s_CachedBytes, 0, BlockDataSize);
- }
- private StringData ReadStringData(int stringIndex)
- {
- m_Stream.Position = m_StringDataOffset + StringDataSize * stringIndex;
- m_Stream.Read(s_CachedBytes, 0, StringDataSize);
- return Utility.Marshal.BytesToStructure<StringData>(StringDataSize, s_CachedBytes);
- }
- private void WriteStringData(int stringIndex, StringData stringData)
- {
- Utility.Marshal.StructureToBytes(stringData, StringDataSize, s_CachedBytes);
- m_Stream.Position = m_StringDataOffset + StringDataSize * stringIndex;
- m_Stream.Write(s_CachedBytes, 0, StringDataSize);
- }
- private static void CalcOffsets(FileSystem fileSystem)
- {
- fileSystem.m_BlockDataOffset = HeaderDataSize;
- fileSystem.m_StringDataOffset = fileSystem.m_BlockDataOffset + BlockDataSize * fileSystem.m_HeaderData.MaxBlockCount;
- fileSystem.m_FileDataOffset = (int)GetUpBoundClusterOffset(fileSystem.m_StringDataOffset + StringDataSize * fileSystem.m_HeaderData.MaxFileCount);
- }
- private static long GetUpBoundClusterOffset(long offset)
- {
- return (offset - 1L + ClusterSize) / ClusterSize * ClusterSize;
- }
- private static int GetUpBoundClusterCount(long length)
- {
- return (int)((length - 1L + ClusterSize) / ClusterSize);
- }
- private static long GetClusterOffset(int clusterIndex)
- {
- return (long)ClusterSize * clusterIndex;
- }
- }
- }
|