//------------------------------------------------------------ // Game Framework // Copyright © 2013-2021 Jiang Yin. All rights reserved. // Homepage: https://gameframework.cn/ // Feedback: mailto:ellan@gameframework.cn //------------------------------------------------------------ using System; using System.IO; namespace GameFramework.FileSystem { /// /// 文件系统流。 /// public abstract class FileSystemStream { /// /// 缓存二进制流的长度。 /// protected const int CachedBytesLength = 0x1000; /// /// 缓存二进制流。 /// protected static readonly byte[] s_CachedBytes = new byte[CachedBytesLength]; /// /// 获取或设置文件系统流位置。 /// protected internal abstract long Position { get; set; } /// /// 获取文件系统流长度。 /// protected internal abstract long Length { get; } /// /// 设置文件系统流长度。 /// /// 要设置的文件系统流的长度。 protected internal abstract void SetLength(long length); /// /// 定位文件系统流位置。 /// /// 要定位的文件系统流位置的偏移。 /// 要定位的文件系统流位置的方式。 protected internal abstract void Seek(long offset, SeekOrigin origin); /// /// 从文件系统流中读取一个字节。 /// /// 读取的字节,若已经到达文件结尾,则返回 -1。 protected internal abstract int ReadByte(); /// /// 从文件系统流中读取二进制流。 /// /// 存储读取文件内容的二进制流。 /// 存储读取文件内容的二进制流的起始位置。 /// 存储读取文件内容的二进制流的长度。 /// 实际读取了多少字节。 protected internal abstract int Read(byte[] buffer, int startIndex, int length); /// /// 从文件系统流中读取二进制流。 /// /// 存储读取文件内容的二进制流。 /// 存储读取文件内容的二进制流的长度。 /// 实际读取了多少字节。 protected internal int Read(Stream stream, int length) { int bytesRead = 0; int bytesLeft = length; while ((bytesRead = Read(s_CachedBytes, 0, bytesLeft < CachedBytesLength ? bytesLeft : CachedBytesLength)) > 0) { bytesLeft -= bytesRead; stream.Write(s_CachedBytes, 0, bytesRead); } Array.Clear(s_CachedBytes, 0, CachedBytesLength); return length - bytesLeft; } /// /// 向文件系统流中写入一个字节。 /// /// 要写入的字节。 protected internal abstract void WriteByte(byte value); /// /// 向文件系统流中写入二进制流。 /// /// 存储写入文件内容的二进制流。 /// 存储写入文件内容的二进制流的起始位置。 /// 存储写入文件内容的二进制流的长度。 protected internal abstract void Write(byte[] buffer, int startIndex, int length); /// /// 向文件系统流中写入二进制流。 /// /// 存储写入文件内容的二进制流。 /// 存储写入文件内容的二进制流的长度。 protected internal void Write(Stream stream, int length) { int bytesRead = 0; int bytesLeft = length; while ((bytesRead = stream.Read(s_CachedBytes, 0, bytesLeft < CachedBytesLength ? bytesLeft : CachedBytesLength)) > 0) { bytesLeft -= bytesRead; Write(s_CachedBytes, 0, bytesRead); } Array.Clear(s_CachedBytes, 0, CachedBytesLength); } /// /// 将文件系统流立刻更新到存储介质中。 /// protected internal abstract void Flush(); /// /// 关闭文件系统流。 /// protected internal abstract void Close(); } }