UnmanagedMemoryStream.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. //
  2. // System.IO.UnmanagedMemoryStream.cs
  3. //
  4. // Copyright (C) 2006 Sridhar Kulkarni, All Rights Reserved
  5. //
  6. // Authors:
  7. // Sridhar Kulkarni ([email protected])
  8. // Gert Driesen ([email protected])
  9. // Sebastien Pouliot <[email protected]>
  10. //
  11. // Copyright (C) 2005-2006, 2009 Novell, Inc (http://www.novell.com)
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.IO;
  34. using System.Runtime.InteropServices;
  35. using System.Threading;
  36. using System.Threading.Tasks;
  37. namespace System.IO
  38. {
  39. public class UnmanagedMemoryStream : Stream
  40. {
  41. long length;
  42. internal bool closed;
  43. long capacity;
  44. FileAccess fileaccess;
  45. IntPtr initial_pointer;
  46. long initial_position;
  47. long current_position;
  48. SafeBuffer safebuffer;
  49. Task<int> read_task;
  50. internal event EventHandler Closed;
  51. #region Constructor
  52. protected UnmanagedMemoryStream()
  53. {
  54. closed = true;
  55. }
  56. [CLSCompliantAttribute(false)]
  57. public unsafe UnmanagedMemoryStream (byte *pointer, long length) :
  58. this (pointer, length, length, FileAccess.Read)
  59. {
  60. }
  61. [CLSCompliantAttribute(false)]
  62. public unsafe UnmanagedMemoryStream (byte *pointer, long length, long capacity, FileAccess access)
  63. {
  64. closed = true;
  65. Initialize (pointer, length, capacity, access);
  66. }
  67. public UnmanagedMemoryStream (SafeBuffer buffer, long offset, long length) :
  68. this (buffer, offset, length, FileAccess.Read)
  69. {
  70. }
  71. public UnmanagedMemoryStream (SafeBuffer buffer, long offset, long length, FileAccess access)
  72. {
  73. closed = true;
  74. Initialize (buffer, offset, length, access);
  75. }
  76. #endregion
  77. #region Properties
  78. public override bool CanRead {
  79. get {
  80. return (!closed && (fileaccess != FileAccess.Write));
  81. }
  82. }
  83. public override bool CanSeek {
  84. get {
  85. return !closed;
  86. }
  87. }
  88. public override bool CanWrite {
  89. get {
  90. return (!closed && (fileaccess != FileAccess.Read));
  91. }
  92. }
  93. public long Capacity {
  94. get {
  95. if (closed)
  96. throw new ObjectDisposedException("The stream is closed");
  97. else
  98. return (capacity);
  99. }
  100. }
  101. public override long Length {
  102. get {
  103. if (closed)
  104. throw new ObjectDisposedException("The stream is closed");
  105. else
  106. return (length);
  107. }
  108. }
  109. public override long Position {
  110. get {
  111. if (closed)
  112. throw new ObjectDisposedException("The stream is closed");
  113. return (current_position);
  114. }
  115. set {
  116. if (closed)
  117. throw new ObjectDisposedException("The stream is closed");
  118. if (value < 0)
  119. throw new ArgumentOutOfRangeException("value", "Non-negative number required.");
  120. if (value > (long)Int32.MaxValue)
  121. throw new ArgumentOutOfRangeException("value", "The position is larger than Int32.MaxValue.");
  122. current_position = value;
  123. }
  124. }
  125. [CLSCompliantAttribute (false)]
  126. public unsafe byte* PositionPointer {
  127. get {
  128. if (safebuffer != null)
  129. throw new NotSupportedException ("Not supported when using SafeBuffer");
  130. if (closed)
  131. throw new ObjectDisposedException("The stream is closed");
  132. if (current_position >= length)
  133. throw new IndexOutOfRangeException ("value");
  134. return (byte *) initial_pointer + current_position;
  135. }
  136. set {
  137. if (safebuffer != null)
  138. throw new NotSupportedException ("Not supported when using SafeBuffer");
  139. if (closed)
  140. throw new ObjectDisposedException("The stream is closed");
  141. if (value < (byte *)initial_pointer)
  142. throw new IOException ("Address is below the inital address");
  143. Position = value - (byte*) initial_pointer;
  144. }
  145. }
  146. #endregion
  147. #region Methods
  148. public override int Read ([InAttribute] [OutAttribute] byte[] buffer, int offset, int count)
  149. {
  150. if (closed)
  151. throw new ObjectDisposedException("The stream is closed");
  152. if (buffer == null)
  153. throw new ArgumentNullException("buffer");
  154. if (offset < 0)
  155. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  156. if (count < 0)
  157. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  158. if ((buffer.Length - offset) < count)
  159. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  160. if (fileaccess == FileAccess.Write)
  161. throw new NotSupportedException("Stream does not support reading");
  162. if (current_position >= length)
  163. return 0;
  164. int progress = current_position + count < length ? count : (int) (length - current_position);
  165. if (safebuffer != null) {
  166. unsafe {
  167. byte *ptr = null;
  168. try {
  169. safebuffer.AcquirePointer (ref ptr);
  170. Marshal.Copy (new IntPtr (ptr + current_position), buffer, offset, progress);
  171. } finally {
  172. if (ptr != null)
  173. safebuffer.ReleasePointer ();
  174. }
  175. }
  176. } else
  177. {
  178. Marshal.Copy (new IntPtr (initial_pointer.ToInt64 () + current_position), buffer, offset, progress);
  179. }
  180. current_position += progress;
  181. return progress;
  182. }
  183. public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  184. {
  185. if (buffer == null)
  186. throw new ArgumentNullException("buffer");
  187. if (offset < 0)
  188. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  189. if (count < 0)
  190. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  191. if ((buffer.Length - offset) < count)
  192. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  193. if (cancellationToken.IsCancellationRequested)
  194. return TaskConstants<int>.Canceled;
  195. try {
  196. count = Read (buffer, offset, count);
  197. // Try not to allocate a new task for every buffer read
  198. if (read_task == null || read_task.Result != count)
  199. read_task = Task<int>.FromResult (count);
  200. return read_task;
  201. } catch (Exception ex) {
  202. return Task.FromException<int> (ex);
  203. }
  204. }
  205. public override int ReadByte ()
  206. {
  207. if (closed)
  208. throw new ObjectDisposedException("The stream is closed");
  209. if (fileaccess== FileAccess.Write)
  210. throw new NotSupportedException("Stream does not support reading");
  211. if (current_position >= length)
  212. return (-1);
  213. if (safebuffer != null) {
  214. unsafe {
  215. byte *ptr = null;
  216. try {
  217. safebuffer.AcquirePointer (ref ptr);
  218. return (int) Marshal.ReadByte (new IntPtr (ptr), (int) current_position++);
  219. } finally {
  220. if (ptr != null)
  221. safebuffer.ReleasePointer ();
  222. }
  223. }
  224. } else
  225. {
  226. return (int) Marshal.ReadByte(initial_pointer, (int) current_position++);
  227. }
  228. }
  229. public override long Seek (long offset, SeekOrigin loc)
  230. {
  231. if (closed)
  232. throw new ObjectDisposedException("The stream is closed");
  233. long refpoint;
  234. switch(loc) {
  235. case SeekOrigin.Begin:
  236. if (offset < 0)
  237. throw new IOException("An attempt was made to seek before the beginning of the stream");
  238. refpoint = initial_position;
  239. break;
  240. case SeekOrigin.Current:
  241. refpoint = current_position;
  242. break;
  243. case SeekOrigin.End:
  244. refpoint = length;
  245. break;
  246. default:
  247. throw new ArgumentException("Invalid SeekOrigin option");
  248. }
  249. refpoint += offset;
  250. if (refpoint < initial_position)
  251. throw new IOException("An attempt was made to seek before the beginning of the stream");
  252. current_position = refpoint;
  253. return(current_position);
  254. }
  255. public override void SetLength (long value)
  256. {
  257. if (safebuffer != null)
  258. throw new NotSupportedException ("Not supported when using SafeBuffer");
  259. if (closed)
  260. throw new ObjectDisposedException("The stream is closed");
  261. if (value < 0)
  262. throw new ArgumentOutOfRangeException("length", "Non-negative number required.");
  263. if (value > capacity)
  264. throw new IOException ("Unable to expand length of this stream beyond its capacity.");
  265. if (fileaccess == FileAccess.Read)
  266. throw new NotSupportedException ("Stream does not support writing.");
  267. length = value;
  268. if (length < current_position)
  269. current_position = length;
  270. }
  271. public override void Flush ()
  272. {
  273. if (closed)
  274. throw new ObjectDisposedException("The stream is closed");
  275. //This method performs no action for this class
  276. //but is included as part of the Stream base class
  277. }
  278. public override Task FlushAsync (CancellationToken cancellationToken)
  279. {
  280. if (cancellationToken.IsCancellationRequested)
  281. return TaskConstants.Canceled;
  282. try {
  283. Flush ();
  284. return TaskConstants.Finished;
  285. } catch (Exception ex) {
  286. return Task.FromException<object> (ex);
  287. }
  288. }
  289. protected override void Dispose (bool disposing)
  290. {
  291. if (closed)
  292. return;
  293. closed = true;
  294. if (Closed != null)
  295. Closed (this, null);
  296. }
  297. public override void Write (byte[] buffer, int offset, int count)
  298. {
  299. if (closed)
  300. throw new ObjectDisposedException("The stream is closed");
  301. if (buffer == null)
  302. throw new ArgumentNullException("The buffer parameter is a null reference");
  303. if (offset < 0)
  304. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  305. if (count < 0)
  306. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  307. if ((buffer.Length - offset) < count)
  308. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  309. if (current_position > capacity - count)
  310. throw new NotSupportedException ("Unable to expand length of this stream beyond its capacity.");
  311. if (fileaccess == FileAccess.Read)
  312. throw new NotSupportedException ("Stream does not support writing.");
  313. if (safebuffer != null) {
  314. unsafe {
  315. byte *dest = null;
  316. try {
  317. safebuffer.AcquirePointer (ref dest);
  318. fixed (byte *src = buffer) {
  319. dest += current_position;
  320. String.memcpy (dest, src + offset, count);
  321. }
  322. } finally {
  323. if (dest != null)
  324. safebuffer.ReleasePointer ();
  325. }
  326. }
  327. } else
  328. {
  329. unsafe {
  330. fixed (byte *src = buffer) {
  331. byte *dest = (byte *) initial_pointer + current_position;
  332. String.memcpy (dest, src + offset, count);
  333. }
  334. }
  335. }
  336. current_position += count;
  337. if (current_position > length)
  338. length = current_position;
  339. }
  340. public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  341. {
  342. if (buffer == null)
  343. throw new ArgumentNullException("The buffer parameter is a null reference");
  344. if (offset < 0)
  345. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  346. if (count < 0)
  347. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  348. if ((buffer.Length - offset) < count)
  349. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  350. if (current_position > capacity - count)
  351. throw new NotSupportedException ("Unable to expand length of this stream beyond its capacity.");
  352. if (cancellationToken.IsCancellationRequested)
  353. return TaskConstants.Canceled;
  354. try {
  355. Write (buffer, offset, count);
  356. return TaskConstants.Finished;
  357. } catch (Exception ex) {
  358. return Task.FromException<object> (ex);
  359. }
  360. }
  361. public override void WriteByte (byte value)
  362. {
  363. if (closed)
  364. throw new ObjectDisposedException("The stream is closed");
  365. if (current_position == capacity)
  366. throw new NotSupportedException("The current position is at the end of the capacity of the stream");
  367. if (fileaccess == FileAccess.Read)
  368. throw new NotSupportedException("Stream does not support writing.");
  369. if (safebuffer != null) {
  370. unsafe {
  371. byte *dest = null;
  372. try {
  373. safebuffer.AcquirePointer (ref dest);
  374. dest += current_position++;
  375. *dest = value;
  376. } finally {
  377. if (dest != null)
  378. safebuffer.ReleasePointer ();
  379. }
  380. }
  381. } else
  382. {
  383. unsafe {
  384. byte *dest = (byte *) initial_pointer + (int) current_position++;
  385. *dest = value;
  386. }
  387. }
  388. if (current_position > length)
  389. length = current_position;
  390. }
  391. [CLSCompliant (false)]
  392. protected unsafe void Initialize (byte* pointer, long length,
  393. long capacity,
  394. FileAccess access)
  395. {
  396. if (pointer == null)
  397. throw new ArgumentNullException("pointer");
  398. if (length < 0)
  399. throw new ArgumentOutOfRangeException("length", "Non-negative number required.");
  400. if (capacity < 0)
  401. throw new ArgumentOutOfRangeException("capacity", "Non-negative number required.");
  402. if (length > capacity)
  403. throw new ArgumentOutOfRangeException("length", "The length cannot be greater than the capacity.");
  404. if ((access < FileAccess.Read) || (access > FileAccess.ReadWrite))
  405. throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
  406. if (!closed)
  407. throw new InvalidOperationException ("Called Initialize twice");
  408. fileaccess = access;
  409. this.length = length;
  410. this.capacity = capacity;
  411. initial_position = 0;
  412. current_position = initial_position;
  413. initial_pointer = new IntPtr ((void*)pointer);
  414. closed = false;
  415. }
  416. protected void Initialize (SafeBuffer buffer, long offset, long length, FileAccess access)
  417. {
  418. if (buffer == null)
  419. throw new ArgumentNullException ("buffer");
  420. if (offset < 0)
  421. throw new ArgumentOutOfRangeException ("offset");
  422. if (length < 0)
  423. throw new ArgumentOutOfRangeException ("length");
  424. ulong blength = buffer.ByteLength;
  425. if ((blength - (ulong) length) < (ulong) offset)
  426. throw new ArgumentException ("Invalid offset and/or length");
  427. if (access < FileAccess.Read || access > FileAccess.ReadWrite)
  428. throw new ArgumentOutOfRangeException ("access");
  429. if (!closed)
  430. throw new InvalidOperationException ("Called Initialize twice");
  431. this.length = length;
  432. this.capacity = length;
  433. this.fileaccess = access;
  434. this.safebuffer = buffer;
  435. initial_position = offset;
  436. current_position = offset;
  437. closed = false;
  438. }
  439. #endregion
  440. }
  441. }