The beginnings of a Coyote file system mock object for Task Programming model...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Security.Permissions; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace CoyoteTests | |
{ | |
internal class FileSystemMock | |
{ | |
ConcurrentDictionary<string, byte[]> files = new ConcurrentDictionary<string, byte[]>(); | |
ConcurrentDictionary<string, OpenFileStream> openFiles = new ConcurrentDictionary<string, OpenFileStream>(); | |
public async Task<Stream> OpenAsync(string path) | |
{ | |
// model some asynchrony in the file system with a delay. | |
await Task.Delay(1); | |
byte[] data; | |
if (!files.TryGetValue(path, out data)) | |
{ | |
throw new FileNotFoundException(path); | |
} | |
var f = new OpenFileStream(path, this); | |
if (!openFiles.TryAdd(path, f)) | |
{ | |
throw new FileLoadException("File is locked by another task"); | |
} | |
else | |
{ | |
f.Open(data); | |
} | |
return s; | |
} | |
class OpenFileStream : Stream | |
{ | |
string filename; | |
MemoryStream memoryStream; | |
FileSystemMock owner; | |
byte[] oldData; | |
internal OpenFileStream(string path, FileSystemMock owner) | |
{ | |
this.filename = path; | |
this.owner = owner; | |
} | |
public void Open(byte[] data) | |
{ | |
this.oldData = data; | |
this.memoryStream = new MemoryStream(data); | |
} | |
public override bool CanRead => memoryStream.CanRead; | |
public override bool CanSeek => memoryStream.CanSeek; | |
public override bool CanWrite => memoryStream.CanWrite; | |
public override long Length => memoryStream.Length; | |
public override long Position { get => memoryStream.Position; set => memoryStream.Position = value; } | |
public override void Flush() => memoryStream.Flush(); | |
public override int Read(byte[] buffer, int offset, int count) => memoryStream.Read(buffer, offset, count); | |
public override long Seek(long offset, SeekOrigin origin) => memoryStream.Seek(offset, origin); | |
public override void SetLength(long value) => memoryStream.SetLength(value); | |
public override void Write(byte[] buffer, int offset, int count) => memoryStream.Write(buffer, offset, count); | |
protected override void Dispose(bool disposing) | |
{ | |
if (this.memoryStream != null) | |
{ | |
byte[] newData = this.memoryStream.ToArray(); | |
this.memoryStream.Dispose(); | |
this.owner.openFiles.Remove(this.filename, out _); | |
this.owner.files.TryUpdate(this.filename, this.oldData, newData); | |
} | |
base.Dispose(disposing); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment