UnmanagedMemoryStream.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. namespace System.IO
  36. {
  37. public class UnmanagedMemoryStream : Stream
  38. {
  39. long length;
  40. bool closed;
  41. long capacity;
  42. FileAccess fileaccess;
  43. IntPtr initial_pointer;
  44. long initial_position;
  45. long current_position;
  46. #if NET_4_0
  47. SafeBuffer safebuffer;
  48. #endif
  49. internal event EventHandler Closed;
  50. #region Constructor
  51. protected UnmanagedMemoryStream()
  52. {
  53. closed = true;
  54. }
  55. [CLSCompliantAttribute(false)]
  56. public unsafe UnmanagedMemoryStream (byte *pointer, long length) :
  57. this (pointer, length, length, FileAccess.Read)
  58. {
  59. }
  60. [CLSCompliantAttribute(false)]
  61. public unsafe UnmanagedMemoryStream (byte *pointer, long length, long capacity, FileAccess access)
  62. {
  63. closed = true;
  64. Initialize (pointer, length, capacity, access);
  65. }
  66. #if NET_4_0
  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. #endif
  77. #endregion
  78. #region Properties
  79. public override bool CanRead {
  80. get {
  81. return (!closed && (fileaccess != FileAccess.Write));
  82. }
  83. }
  84. public override bool CanSeek {
  85. get {
  86. return !closed;
  87. }
  88. }
  89. public override bool CanWrite {
  90. get {
  91. return (!closed && (fileaccess != FileAccess.Read));
  92. }
  93. }
  94. public long Capacity {
  95. get {
  96. if (closed)
  97. throw new ObjectDisposedException("The stream is closed");
  98. else
  99. return (capacity);
  100. }
  101. }
  102. public override long Length {
  103. get {
  104. if (closed)
  105. throw new ObjectDisposedException("The stream is closed");
  106. else
  107. return (length);
  108. }
  109. }
  110. public override long Position {
  111. get {
  112. if (closed)
  113. throw new ObjectDisposedException("The stream is closed");
  114. return (current_position);
  115. }
  116. set {
  117. if (closed)
  118. throw new ObjectDisposedException("The stream is closed");
  119. if (value < 0)
  120. throw new ArgumentOutOfRangeException("value", "Non-negative number required.");
  121. if (value > (long)Int32.MaxValue)
  122. throw new ArgumentOutOfRangeException("value", "The position is larger than Int32.MaxValue.");
  123. current_position = value;
  124. }
  125. }
  126. [CLSCompliantAttribute (false)]
  127. public unsafe byte* PositionPointer {
  128. get {
  129. #if NET_4_0
  130. if (safebuffer != null)
  131. throw new NotSupportedException ("Not supported when using SafeBuffer");
  132. #endif
  133. if (closed)
  134. throw new ObjectDisposedException("The stream is closed");
  135. if (current_position >= length)
  136. throw new IndexOutOfRangeException ("value");
  137. return (byte *) initial_pointer + current_position;
  138. }
  139. set {
  140. #if NET_4_0
  141. if (safebuffer != null)
  142. throw new NotSupportedException ("Not supported when using SafeBuffer");
  143. #endif
  144. if (closed)
  145. throw new ObjectDisposedException("The stream is closed");
  146. if (value < (byte *)initial_pointer)
  147. throw new IOException ("Address is below the inital address");
  148. Position = value - (byte*) initial_pointer;
  149. }
  150. }
  151. #endregion
  152. #region Methods
  153. public override int Read ([InAttribute] [OutAttribute] byte[] buffer, int offset, int count)
  154. {
  155. if (closed)
  156. throw new ObjectDisposedException("The stream is closed");
  157. if (buffer == null)
  158. throw new ArgumentNullException("buffer");
  159. if (offset < 0)
  160. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  161. if (count < 0)
  162. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  163. if ((buffer.Length - offset) < count)
  164. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  165. if (fileaccess == FileAccess.Write)
  166. throw new NotSupportedException("Stream does not support reading");
  167. if (current_position >= length)
  168. return 0;
  169. int progress = current_position + count < length ? count : (int) (length - current_position);
  170. #if NET_4_0
  171. if (safebuffer != null) {
  172. unsafe {
  173. byte *ptr = null;
  174. try {
  175. safebuffer.AcquirePointer (ref ptr);
  176. Marshal.Copy (new IntPtr (ptr + current_position), buffer, offset, progress);
  177. } finally {
  178. if (ptr != null)
  179. safebuffer.ReleasePointer ();
  180. }
  181. }
  182. } else
  183. #endif
  184. {
  185. Marshal.Copy (new IntPtr (initial_pointer.ToInt64 () + current_position), buffer, offset, progress);
  186. }
  187. current_position += progress;
  188. return progress;
  189. }
  190. public override int ReadByte ()
  191. {
  192. if (closed)
  193. throw new ObjectDisposedException("The stream is closed");
  194. if (fileaccess== FileAccess.Write)
  195. throw new NotSupportedException("Stream does not support reading");
  196. if (current_position >= length)
  197. return (-1);
  198. #if NET_4_0
  199. if (safebuffer != null) {
  200. unsafe {
  201. byte *ptr = null;
  202. try {
  203. safebuffer.AcquirePointer (ref ptr);
  204. return (int) Marshal.ReadByte (new IntPtr (ptr), (int) current_position++);
  205. } finally {
  206. if (ptr != null)
  207. safebuffer.ReleasePointer ();
  208. }
  209. }
  210. } else
  211. #endif
  212. {
  213. return (int) Marshal.ReadByte(initial_pointer, (int) current_position++);
  214. }
  215. }
  216. public override long Seek (long offset, SeekOrigin loc)
  217. {
  218. if (closed)
  219. throw new ObjectDisposedException("The stream is closed");
  220. long refpoint;
  221. switch(loc) {
  222. case SeekOrigin.Begin:
  223. if (offset < 0)
  224. throw new IOException("An attempt was made to seek before the beginning of the stream");
  225. refpoint = initial_position;
  226. break;
  227. case SeekOrigin.Current:
  228. refpoint = current_position;
  229. break;
  230. case SeekOrigin.End:
  231. refpoint = length;
  232. break;
  233. default:
  234. throw new ArgumentException("Invalid SeekOrigin option");
  235. }
  236. refpoint += offset;
  237. if (refpoint < initial_position)
  238. throw new IOException("An attempt was made to seek before the beginning of the stream");
  239. current_position = refpoint;
  240. return(current_position);
  241. }
  242. public override void SetLength (long value)
  243. {
  244. #if NET_4_0
  245. if (safebuffer != null)
  246. throw new NotSupportedException ("Not supported when using SafeBuffer");
  247. #endif
  248. if (closed)
  249. throw new ObjectDisposedException("The stream is closed");
  250. if (value < 0)
  251. throw new ArgumentOutOfRangeException("length", "Non-negative number required.");
  252. if (value > capacity)
  253. throw new IOException ("Unable to expand length of this stream beyond its capacity.");
  254. if (fileaccess == FileAccess.Read)
  255. throw new NotSupportedException ("Stream does not support writing.");
  256. length = value;
  257. if (length < current_position)
  258. current_position = length;
  259. }
  260. public override void Flush ()
  261. {
  262. if (closed)
  263. throw new ObjectDisposedException("The stream is closed");
  264. //This method performs no action for this class
  265. //but is included as part of the Stream base class
  266. }
  267. protected override void Dispose (bool disposing)
  268. {
  269. if (closed)
  270. return;
  271. closed = true;
  272. if (Closed != null)
  273. Closed (this, null);
  274. }
  275. public override void Write (byte[] buffer, int offset, int count)
  276. {
  277. if (closed)
  278. throw new ObjectDisposedException("The stream is closed");
  279. if (buffer == null)
  280. throw new ArgumentNullException("The buffer parameter is a null reference");
  281. if (offset < 0)
  282. throw new ArgumentOutOfRangeException("offset", "Non-negative number required.");
  283. if (count < 0)
  284. throw new ArgumentOutOfRangeException("count", "Non-negative number required.");
  285. if ((buffer.Length - offset) < count)
  286. throw new ArgumentException("The length of the buffer array minus the offset parameter is less than the count parameter");
  287. if (current_position > capacity - count)
  288. throw new NotSupportedException ("Unable to expand length of this stream beyond its capacity.");
  289. if (fileaccess == FileAccess.Read)
  290. throw new NotSupportedException ("Stream does not support writing.");
  291. #if NET_4_0
  292. if (safebuffer != null) {
  293. unsafe {
  294. byte *dest = null;
  295. try {
  296. safebuffer.AcquirePointer (ref dest);
  297. fixed (byte *src = buffer) {
  298. dest += current_position;
  299. String.memcpy (dest, src + offset, count);
  300. }
  301. } finally {
  302. if (dest != null)
  303. safebuffer.ReleasePointer ();
  304. }
  305. }
  306. } else
  307. #endif
  308. {
  309. unsafe {
  310. fixed (byte *src = buffer) {
  311. byte *dest = (byte *) initial_pointer + current_position;
  312. String.memcpy (dest, src + offset, count);
  313. }
  314. }
  315. }
  316. current_position += count;
  317. if (current_position > length)
  318. length = current_position;
  319. }
  320. public override void WriteByte (byte value)
  321. {
  322. if (closed)
  323. throw new ObjectDisposedException("The stream is closed");
  324. if (current_position == capacity)
  325. throw new NotSupportedException("The current position is at the end of the capacity of the stream");
  326. if (fileaccess == FileAccess.Read)
  327. throw new NotSupportedException("Stream does not support writing.");
  328. #if NET_4_0
  329. if (safebuffer != null) {
  330. unsafe {
  331. byte *dest = null;
  332. try {
  333. safebuffer.AcquirePointer (ref dest);
  334. dest += current_position++;
  335. *dest = value;
  336. } finally {
  337. if (dest != null)
  338. safebuffer.ReleasePointer ();
  339. }
  340. }
  341. } else
  342. #endif
  343. {
  344. unsafe {
  345. byte *dest = (byte *) initial_pointer + (int) current_position++;
  346. *dest = value;
  347. }
  348. }
  349. if (current_position > length)
  350. length = current_position;
  351. }
  352. [CLSCompliant (false)]
  353. protected unsafe void Initialize (byte* pointer, long length,
  354. long capacity,
  355. FileAccess access)
  356. {
  357. if (pointer == null)
  358. throw new ArgumentNullException("pointer");
  359. if (length < 0)
  360. throw new ArgumentOutOfRangeException("length", "Non-negative number required.");
  361. if (capacity < 0)
  362. throw new ArgumentOutOfRangeException("capacity", "Non-negative number required.");
  363. if (length > capacity)
  364. throw new ArgumentOutOfRangeException("length", "The length cannot be greater than the capacity.");
  365. if ((access < FileAccess.Read) || (access > FileAccess.ReadWrite))
  366. throw new ArgumentOutOfRangeException ("access", "Enum value was out of legal range.");
  367. if (!closed)
  368. throw new InvalidOperationException ("Called Initialize twice");
  369. fileaccess = access;
  370. this.length = length;
  371. this.capacity = capacity;
  372. initial_position = 0;
  373. current_position = initial_position;
  374. initial_pointer = new IntPtr ((void*)pointer);
  375. closed = false;
  376. }
  377. #if NET_4_0
  378. protected void Initialize (SafeBuffer buffer, long offset, long length, FileAccess access)
  379. {
  380. if (buffer == null)
  381. throw new ArgumentNullException ("buffer");
  382. if (offset < 0)
  383. throw new ArgumentOutOfRangeException ("offset");
  384. if (length < 0)
  385. throw new ArgumentOutOfRangeException ("length");
  386. ulong blength = buffer.ByteLength;
  387. if ((blength - (ulong) length) < (ulong) offset)
  388. throw new ArgumentException ("Invalid offset and/or length");
  389. if (access < FileAccess.Read || access > FileAccess.ReadWrite)
  390. throw new ArgumentOutOfRangeException ("access");
  391. if (!closed)
  392. throw new InvalidOperationException ("Called Initialize twice");
  393. this.length = length;
  394. this.capacity = length;
  395. this.fileaccess = access;
  396. this.safebuffer = buffer;
  397. initial_position = offset;
  398. current_position = offset;
  399. closed = false;
  400. }
  401. #endif
  402. #endregion
  403. }
  404. }