PageRenderTime 39ms CodeModel.GetById 34ms app.highlight 3ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Manos.IO/Manos.IO.Managed/FileStream.cs

http://github.com/jacksonh/manos
C# | 114 lines | 94 code | 20 blank | 0 comment | 12 complexity | c8bade1e7f28857812644ed7b56b408f MD5 | raw file
  1using System;
  2using Manos.IO;
  3using System.Collections.Generic;
  4using System.IO;
  5using Mono.Unix.Native;
  6
  7namespace Manos.IO.Managed
  8{
  9	class FileStream : ManagedByteStream
 10	{
 11		System.IO.FileStream stream;
 12
 13		public FileStream (Context loop, System.IO.FileStream stream, int blockSize)
 14			: base (loop, blockSize)
 15		{
 16			if (loop == null)
 17				throw new ArgumentNullException ("loop");
 18			if (stream == null)
 19				throw new ArgumentNullException ("stream");
 20			
 21			this.stream = stream;
 22		}
 23
 24		public override long Position {
 25			get { return stream.Position; }
 26			set { SeekTo (value); }
 27		}
 28
 29		public override bool CanRead {
 30			get { return stream.CanRead; }
 31		}
 32
 33		public override bool CanSeek {
 34			get { return stream.CanSeek; }
 35		}
 36
 37		public override bool CanWrite {
 38			get { return stream.CanWrite; }
 39		}
 40
 41		public override void SeekBy (long delta)
 42		{
 43			CheckDisposed ();
 44			
 45			stream.Seek (delta, SeekOrigin.Current);
 46		}
 47
 48		public override void SeekTo (long position)
 49		{
 50			CheckDisposed ();
 51			
 52			stream.Seek (position, SeekOrigin.Begin);
 53		}
 54		
 55		protected override void Dispose (bool disposing)
 56		{
 57			if (stream != null) {
 58				stream.Dispose ();
 59				stream = null;
 60			}
 61			base.Dispose (disposing);
 62		}
 63
 64		public override void Write (IEnumerable<ByteBuffer> data)
 65		{
 66			base.Write (data);
 67			ResumeWriting ();
 68		}
 69		
 70		protected override void DoRead ()
 71		{
 72			stream.BeginRead (buffer, 0, buffer.Length, OnReadDone, null);
 73		}
 74
 75		void OnReadDone (IAsyncResult ar)
 76		{
 77			Context.Enqueue (delegate {
 78				if (stream != null) {
 79					ResetReadTimeout ();
 80					int result = stream.EndRead (ar);
 81			
 82					if (result > 0) {
 83						byte [] newBuffer = new byte [result];
 84						Buffer.BlockCopy (buffer, 0, newBuffer, 0, result);
 85						
 86						RaiseData (new ByteBuffer (newBuffer));
 87						DispatchRead ();
 88					} else {
 89						PauseReading ();
 90						RaiseEndOfStream ();
 91					}
 92				}
 93			});
 94		}
 95		
 96		protected override WriteResult WriteSingleFragment (ByteBuffer fragment)
 97		{
 98			stream.BeginWrite (fragment.Bytes, fragment.Position, fragment.Length, OnWriteDone, null);
 99			return WriteResult.Consume;
100		}
101
102		void OnWriteDone (IAsyncResult ar)
103		{
104			Context.Enqueue (delegate {
105				if (stream != null) {
106					ResetWriteTimeout ();
107					stream.EndWrite (ar);
108					HandleWrite ();
109				}
110			});
111		}
112	}
113}
114