datastream.monkey2 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. Namespace std.memory
  2. #rem monkeydoc DataStream class.
  3. #end
  4. Class DataStream Extends std.stream.Stream
  5. #rem monkeydoc Creates a new datastream.
  6. A datastream wraps a databuffer so it can be used as if it were a stream.
  7. In debug mode, a RuntimeError will occur if `offset` or `count` are outside the range of the databuffer.
  8. @param data The databuffer to wrap.
  9. @param offset The starting offset.
  10. @param count The number of bytes.
  11. #end
  12. Method New( buf:DataBuffer,offset:Int=0 )
  13. Self.New( buf,offset,buf.Length-offset )
  14. End
  15. Method New( buf:DataBuffer,offset:Int,count:Int )
  16. DebugAssert( offset>=0 And count>=0 And offset+count<=buf.Length )
  17. _buf=buf
  18. _off=offset
  19. _len=count
  20. _pos=0
  21. End
  22. #rem monkeydoc True if no more data can be read from or written to the stream.
  23. #end
  24. Property Eof:Bool() Override
  25. Return _pos>=_len
  26. End
  27. #rem monkeydoc Current datastream position.
  28. #end
  29. Property Position:Int() Override
  30. Return _pos
  31. End
  32. #rem monkeydoc Current datastream length.
  33. #end
  34. Property Length:Int() Override
  35. Return _len
  36. End
  37. #rem monkeydoc Closes the datastream.
  38. #end
  39. Method OnClose() Override
  40. If Not _buf Return
  41. _buf=Null
  42. _off=0
  43. _pos=0
  44. _len=0
  45. End
  46. #rem monkeydoc Seeks to a position in the datastream.
  47. @param position The position to seek to.
  48. #end
  49. Method Seek( position:Int ) Override
  50. _pos=Clamp( position,0,_len )
  51. End
  52. #rem monkeydoc Reads data from the datastream.
  53. @param buf A pointer to the memory to read the data into.
  54. @param count The number of bytes to read.
  55. @return The number of bytes actually read.
  56. #end
  57. Method Read:Int( buf:Void Ptr,count:Int ) Override
  58. count=Clamp( count,0,_len-_pos )
  59. libc.memcpy( buf,_buf.Data+_off+_pos,count )
  60. _pos+=count
  61. Return count
  62. End
  63. #rem monkeydoc Writes data to the datastream.
  64. @param buf A pointer to the memory to write the data from.
  65. @param count The number of bytes to write.
  66. @return The number of bytes actually written.
  67. #end
  68. Method Write:Int( buf:Void Ptr,count:Int ) Override
  69. count=Clamp( count,0,_len-_pos )
  70. libc.memcpy( _buf.Data+_off+_pos,buf,count )
  71. _pos+=count
  72. Return count
  73. End
  74. Private
  75. Field _buf:DataBuffer
  76. Field _off:Int
  77. Field _pos:Int
  78. Field _len:Int
  79. End