Skip to content
This repository
tree: 0aa29c9ace
Fetching contributors…

Cannot retrieve contributors at this time

file 1094 lines (867 sloc) 31.729 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
module streams

import exceptions:
BoundsException,
IOException,
NotImplementedException,
RangeException,
TypeException,
ValueException

import math:
min

local function clamp(x, lo, hi) =
x < lo ? lo : x > hi ? hi : x

/**
An exception type derived from \tt{IOException} thrown in some APIs when end-of-file is reached.
*/
class EOFException : IOException
{
///
this()
super("Unexpected end of file")
}

/**
An exception type derived from \tt{IOException} thrown in some APIs when stream protocols (behavior,
return values etc.) are not respected.
*/
class StreamProtocolException : IOException
{
///
this(msg: string)
super("Stream protocol error: " ~ msg)
}

/**
A helper function for checking the params to stream \tt{read} and \tt{write} functions.

This ensures that the \tt{offset} and \tt{size} parameters are valid, and throws exceptions if not.

\throws[exceptions.BoundsException] if either \tt{offset} or \tt{size} is invalid.
*/
function checkRWParams(m, offset, size)
{
if(offset < 0 || offset > #m)
throw BoundsException("Invalid offset {} in memblock of size {}".format(offset, #m))

if(size < 0 || size > #m - offset)
throw BoundsException("Invalid size {} in memblock of size {} starting from offset {}".format(size, #m, offset))
}

local checkRWParams = checkRWParams

/**
The base class for stream-based IO.

This class defines the interface that all streams must implement, as well as some helper functions which are implemented in
terms of the user-defined methods. This interface is fairly low-level and is meant to be wrapped by higher-level stream
wrappers and filters.

There are a relatively small number of functions which must be implemented to satisfy the stream interface. Detailed descriptions
of these methods and their behavior is given inside this class, but a quick overview is as follows:

\blist
\li \b{\tt{readable, writable, seekable}} - These simply return bools which indicate whether this stream can be read from,
written to, and seeked.
\li \b{\tt{read, write, seek}} - The real workhorse functions which actually perform the reading, writing, and seeking of the
stream. Each of these only needs to be implemented if the corresponding \tt{-able} method returns \tt{true}.
\li \b{\tt{flush, close, isOpen}} - Miscellaneous optional methods.
\endlist

For any given stream, likely only the first six (or some subset thereof) will have to be implemented.
*/
class Stream
{
_scratch

/**
Constructor. Be sure to call this as \tt{super()} in classes derived from \link{Stream}. While it only checks
that one of \link{readable} and \link{writable} returns true right now, this may change in the future.

\throws[exceptions.IOException] if both \link{readable} and \link{writable} return \tt{false}.
*/
this()
{
if(!:readable() && !:writable())
throw IOException("Stream is neither readable nor writable!")
}

/**
Reads data from the stream into the given memblock.

\param[this] must be readable.
\param[m] is the memblock into which data will be read.
\param[offset] is the offset into \tt{m} where the first byte of data will be placed. Defaults to 0.
\param[size] is the number of bytes to read. Defaults to the size of \tt{m} minus the \tt{offset}.

\returns an integer.

\blist
\li If \tt{size} is 0, this function is a no-op, and the return value is 0.
\li If \tt{size} is nonzero,
\blist
\li If the read is successful, the return value is an integer in the range \tt{[1, size]} and indicates
the number of bytes actually read. Fewer than \tt{size} bytes can be read in a number of non-error
situations. If you need to fill up a buffer, make repeated calls to \tt{read} until the desired number
of bytes has been read. The \link{readExact} method does this for you.
\li If the stream has reached the end of the file, the return value is 0.
\endlist
\endlist

\throws[exceptions.BoundsException] if the \tt{offset} is outside the range \tt{[0, #m]}, or if \tt{size}
is outside the range \tt{[0, #m - offset]}.

\throws[exceptions.IOException] or a derived class if some error occurred.
*/
function read(this: @InStream, m: memblock, offset: int = 0, size: int = #m - offset)
throw NotImplementedException()

/**
Writes data into the stream from the given memblock.

\param[this] must be writable.
\param[m] is the memblock from which data will be written.
\param[offset] is the offset into \tt{m} where the first byte of data will be retrieved. Defaults to 0.
\param[size] is the number of bytes to write. Defaults to the size of \tt{m} minus the \tt{offset}.

\returns an integer.

\blist
\li If \tt{size} is 0, this function is a no-op, and the return value is 0.
\li If \tt{size} is nonzero and the write is successful, the return value is an integer in the range \tt{[1, size]}
and indicates the number of bytes actually written. Fewer than \tt{size} bytes can be written in a number of
non-error situations. If you need to write a whole buffer, make repeated calls to \tt{write} until the desired
number of bytes has been written. The \link{writeExact} method does this for you.
\endlist

\throws[exceptions.BoundsException] if the \tt{offset} is outside the range \tt{[0, #m]}, or if \tt{size}
is outside the range \tt{[0, #m - offset]}.

\throws[exceptions.IOException] or a derived class if some error occurred.
\throws[EOFException] if end-of-file was reached.
*/
function write(this: @OutStream, m: memblock, offset: int = 0, size: int = #m - offset)
throw NotImplementedException()

/**
Changes the position of the stream's read/write position, and reports the new position once changed.

Seeking past the end of a stream may or may not be an error, depending on the kind of stream.

\param[this] must be seekable.
\param[offset] is the position offset, whose meaning depends upon the \tt{where} parameter.
\param[where] is a character indicating the position in the stream from which the new stream position will be calculated.
It can be one of the three following values:

\dlist
\li{\b{\tt{'b'}}} The \tt{offset} is treated as an absolute offset from the beginning of the stream.
\li{\b{\tt{'c'}}} The \tt{offset} is treated as a relative offset from the current read/write position. This means that
negative \tt{offset} values move the read/write position backwards.
\li{\b{\tt{'e'}}} The \tt{offset} is treated as a relative offset from the end of the stream.
\endlist

\returns the new stream position as an absolute position from the beginning of the stream.

\throws[exceptions.IOException] if the resulting stream position would be negative, or if some error occurred.
*/
function seek(this: @SeekStream, offset: int, where: char)
throw NotImplementedException()

/**
Tells whether or not \link{read} can be called on this stream.
\returns a bool indicating such. The default implementation returns \tt{false}.
*/
function readable() = false

/**
Tells whether or not \link{write} can be called on this stream.
\returns a bool indicating such. The default implementation returns \tt{false}.
*/
function writable() = false

/**
Tells whether or not \link{seek} can be called on this stream.
\returns a bool indicating such. The default implementation returns \tt{false}.
*/
function seekable() = false

/**
An optional method used to flush cached data to the stream.

Often buffering schemes are used to improve IO performance, but such schemes mean that the stream and its backing store are
often incoherent. This method is called to force coherency by flushing any buffered data and writing it into the backing store.

The default implementation is simply to do nothing.
*/
function flush() {}

/**
An optional method used to close a stream by releasing any system resources associated with it and preventing any further use.

This method should be allowed to be called more than once, but calls beyond the first should be no-ops.

The default implementation is simply to do nothing.
*/
function close() {}

/**
An optional method used to check whether or not this stream has been closed.

This goes along with the \link{close} method; once \link{close} has been called, this method should return \tt{false}.

\returns a bool indicating whether or not this stream is still open. The default implementation simply returns \tt{true}.
*/
function isOpen() = true

/**
A helper method which attempts to read a block of data fully, making multiple calls to \link{read} as needed.

Since \link{read} may not read all the data for a block in one call, this method exists to automatically make as many calls
to \link{read} as needed to fill the requested block of data. The parameters are identical to those of \link{read}.

\throws[exceptions.IOException] or a derived class if some error occurred.
\throws[EOFException] if end-of-file was reached.
*/
function readExact(m: memblock, offset: int = 0, size: int = #m - offset)
{
checkRWParams(m, offset, size)
local remaining = size

while(remaining > 0)
{
local bytesRead = :read(m, offset, remaining)

if(bytesRead == 0)
throw EOFException()

offset += bytesRead
remaining -= bytesRead
}
}

/**
A helper method which attempts to write a block of data fully, making multiple calls to \link{write} as needed.

Since \link{write} may not write all the data for a block in one call, this method exists to automatically make as many calls
to \link{write} as needed to write the requested block of data. The parameters are identical to those of \link{write}.

\throws[exceptions.IOException] or a derived class if some error occurred.
\throws[EOFException] if end-of-file was reached.
*/
function writeExact(m: memblock, offset: int = 0, size: int = #m - offset)
{
checkRWParams(m, offset, size)
local remaining = size

while(remaining > 0)
{
local bytesWritten = :write(m, offset, remaining)
offset += bytesWritten
remaining -= bytesWritten
}
}

/**
Skips forward a given number of bytes.

The stream need not be seekable in order to skip forward. If it is not seekable, data will simply be read into a scratch buffer
and discarded until the desired number of bytes have been skipped. If it is seekable, this will simply call \link{seek} to seek
forward \tt{dist} bytes.

\param[this] must be readable, and may optionally be seekable.
\param[dist] is the number of bytes to skip. Can be 0.

\throws[exceptions.RangeException] if \tt{dist} is negative.
\throws[exceptions.IOException] or a derived class if some error occurred.
\throws[EOFException] if end-of-file was reached.
*/
function skip(this: @InStream, dist: int)
{
if(dist < 0)
throw RangeException("Invalid skip distance ({})".format(dist))
else if(dist == 0)
return

if(:seekable())
{
:seek(dist, 'c')
return
}

:flush()

:_scratch ?= memblock.new(4096)
local buf = :_scratch

while(dist > 0)
{
local bytesRead = :readExact(buf, 0, min(dist, #buf))

if(bytesRead == 0)
throw EOFException()

dist -= numBytes
}
}

/**
Reads all remaining data from the stream up to end-of-file into a memblock.

This will call \link{read} as many times as needed until it indicates that the end of file has been reached.

\param[this] must be readable.
\param[m] is an optional memblock to use as the buffer to hold the read data. If one is given, it will be resized to hold the
read data. If it is not given, a new memblock will be used instead.

\returns the memblock holding the read data.
*/
function readAll(this: @InStream, m: memblock = null)
{
if(m is null)
m = memblock.new(4096)
else if(#m < 4096)
#m = 4096

local offs = 0

while(true)
{
local numBytes = :read(m, offs)

if(numBytes == 0)
break

offs += numBytes

if(#m < offs + 4096)
#m = offs + 4096
}

#m = offs
return m
}

/**
Copies data from another stream into this one.

The data is copied in blocks of 4096 bytes at a time.

\param[this] must be writable.
\param[s] is the source stream from which the data will be read, and must be readable.
\param[size] is the number of bytes to copy, or -1 to mean all data until \tt{s} reaches end-of-file.

\throws[exceptions.RangeException] if \tt{size < -1}.
\throws[EOFException] if \tt{size > 0} and end-of-file was reached before copying could finish.
*/
function copy(this: @OutStream, s: @InStream, size: int = -1)
{
:_scratch ?= memblock.new(4096)
local buf = :_scratch

if(size < -1)
throw RangeException("Invalid size: {}".format(size))

if(size == -1)
{
while(true)
{
local numRead = s.read(buf)

if(numRead == 0)
break

:writeExact(buf, 0, numRead)
}
}
else
{
local remaining = size

while(remaining > 0)
{
local numRead = s.read(buf, 0, min(remaining, #buf))

if(numRead == 0)
throw EOFException()

:writeExact(buf, 0, numRead)
remaining -= numRead
}
}
}

/**
Sets or gets the absolute position in the stream, as a convenience.

\param[this] must be seekable.
\param[pos] is either the new read/write position, measured in bytes from the beginning of the stream, or \tt{null}.

\returns the new position if \tt{pos} was non-null, or the current position if \tt{pos} was \tt{null}.
*/
function position(this: @SeekStream, pos: int|null)
{
if(pos is null)
return :seek(0, 'c')
else
return :seek(pos, 'b')
}

/**
Returns the size of the stream in bytes.

It does this by seeking to the end of the stream and getting the position, then seeking back to where it was before
calling this method. As a result this method can cause buffered data to be flushed.

\param[this] must be seekable.

\returns an integer indicating how many bytes long this stream is.
*/
function size(this: @SeekStream)
{
local pos = :position()
local ret = :seek(0, 'e')
:position(pos)
return ret
}
}

/**
These are meant to be used as custom parameter type constraints, to ensure that a stream parameter supports certain operations.

All of these ensure that \tt{s} is derived from \link{Stream}. The \tt{in} functions ensure that \tt{s.readable()} returns true;
the \tt{out} functions ensure that \tt{s.writable()} returns true; and the \tt{seek} functions ensure that \tt{s.seekable()}
returns true. An example of use:

\code
// Expects the dest stream to be writable and the src stream to be readable
function copyBlock(dest: @OutStream, src: @InStream) { ... }

// Finds the directory section in a ZIP file and reads it; expects the stream to be readable and seekable.
function readZIPDirectory(s: @InSeekStream) { ... }
\endcode

It's a good idea to use only what you need and not over-request features; for instance, if you're never going to write to the
stream, don't use an \tt{out} function.

\param[s] the stream object to test.
\returns a bool telling whether or not it satisfies the constraints.
*/
function InStream(s) = s as Stream && s.readable()
function OutStream(s) = s as Stream && s.writable() /// ditto
function InoutStream(s) = s as Stream && s.readable() && s.writable() /// ditto
function SeekStream(s) = s as Stream && s.seekable() /// ditto
function InSeekStream(s) = s as Stream && s.readable() && s.seekable() /// ditto
function OutSeekStream(s) = s as Stream && s.writable() && s.seekable() /// ditto
function InoutSeekStream(s) = s as Stream && s.readable() && s.writable() && s.seekable() /// ditto

/**
Implements a readable, writable, seekable stream that uses a memblock as its data backing store.

This is a very useful kind of stream. With it you can redirect stream operations that would normally go to a file to memory
instead. It can often be much faster to read in a large chunk of a file, or a file in its entirety, and then do processing
in memory. This is also useful for building up data to be sent over networks or such.

The backing memblock can be one you provide, or it can use its own. The memblock will be grown automatically when data is
written past its end.
*/
class MemblockStream : Stream
{
_mb
_pos = 0

/**
Constructor.

\param[mb] is the memblock to use as the backing store. If none is given, a new zero-size memblock will be used instead.
*/
this(mb: memblock = memblock.new(0))
{
:_mb = mb
super()
}

/**
Implmentation of \link{Stream.read}.
*/
function read(m: memblock, offset: int = 0, size: int = #m - offset)
{
if(:_pos >= #:_mb)
return 0

checkRWParams(m, offset, size)

if(size == 0)
return 0

local numBytes = min(size, #:_mb - :pos)
m.rawCopy(offset, :_mb, :_pos, numBytes)
:_pos += numBytes
return numBytes
}

/**
Implmentation of \link{Stream.write}.

If there is not enough space in the memblock to hold the new data, the memblock's size will be expanded to accommodate.
*/
function write(m: memblock, offset: int = 0, size: int = #m - offset)
{
checkRWParams(m, offset, size)

if(size == 0)
return 0

local bytesLeft = #:_mb - :_pos

if(size > bytesLeft)
#:_mb += size - bytesLeft

:_mb.rawCopy(:_pos, m, offset, size)
:_pos += size
return size
}

/**
Implmentation of \link{Stream.seek}.

If you seek past the end of the memblock, the memblock will be resized to the new offset. This is to match the behavior
of seeking on files.

\throws[exceptions.ValueException] if \tt{where} is invalid.
\throws[exceptions.IOException] if the resulting offset is negative.
*/
function seek(offset: int, where: char)
{
switch(where)
{
case 'b': break
case 'c': offset += :_pos; break
case 'e': offset += #:_mb; break
default: throw ValueException("Invalid seek type '{}'".format(where))
}

if(offset < 0)
throw IOException("Invalid seek offset")

if(offset > #:_mb)
#:_mb = offset

:_pos = offset
return offset
}

/**
Implementations of \link{Stream.readable}, \link{Stream.writable}, and \link{Stream.seekable}. All return true.
*/
function readable() = true
function writable() = true /// ditto
function seekable() = true /// ditto

/**
Gets the backing memblock.

It's probably best not to change the size of the memblock while it's still being used by the stream.

\returns the backing memblock.
*/
function getBacking() = :_mb
}

local function cropPartial(s: memblock, pos: int)
{
local i = pos - 1

while(i > 0)
{
local b = s[i]

if(!(b & 0x80))
break

if((b & 0xC0) == 0xC0)
{
local d = pos - i

if(b & 0x20)
d--

if(b & 0x10)
d--

if(d == 2)
i = pos

return i
}
else
i--
}

return pos
}

class UTF8Stream
{
stream
readBuf
writeBuf
chunks

bufPos = 0
bound = 0

shouldFlush = false
dirty = false

this(s: Stream)
{
:stream = s
:readBuf = memblock.new(4096)
:writeBuf = memblock.new(0)
:chunks = []
}

function readln()
{
if(:bound == 0)
{
:_readMore(:bufPos)

if(:bound == 0)
return null
}

#:chunks = 0
local readBuf = :readBuf

while main(:bound > 0)
{
local start = :bufPos

for(; :bufPos < :bound; :bufPos++)
{
if(readBuf[:bufPos] == 10)
{
:chunks ~= string.fromRawUnicode(readBuf, start, :bufPos)
:bufPos++
break main
}
}

local realEnd = cropPartial(readBuf, :bufPos)

:chunks ~= string.fromRawUnicode(readBuf, start, realEnd)

if(realEnd < :bufPos)
{
for(local i, j = 0, realEnd; j < :bufPos; i++, j++)
readBuf[i] = readBuf[j]
}

:_readMore(:bufPos - realEnd)
}

local ret = "".join(:chunks)
#:chunks = 0

if(#ret && ret[-1] == '\r')
#ret--

return ret
}

function iterator(idx: int)
{
if(local ret = :readln())
return idx + 1, ret
}

function opApply(_)
return :iterator, this, 0

function write(vararg)
{
for(i: 0 .. #vararg)
:stream.write(toString(vararg[i]).toRawUnicode(8, :writeBuf))
}

function writeln(vararg)
{
:write(vararg)
:write("\n")

if(:shouldFlush)
:stream.flush()
}

function writef(fmt: string, vararg)
{
:stream.write(fmt.format(vararg).toRawUnicode(8, :writeBuf))
}

function writefln(fmt: string, vararg)
{
:writef(fmt, vararg)
:write("\n")

if(:shouldFlush)
:stream.flush()
}

function flushOnNL(f: bool)
:shouldFlush = f

function _readMore(start: int)
{
:bufPos = 0
:bound = :stream.read(:readBuf, start)
}
}

/**
A base class for types of streams which expand the capabilities of another stream without obscuring the underlying stream
interface.

It takes a stream object and implements all of the \link{Stream} interface methods as simply passthroughs to the underlying
stream object. Subclasses can then add methods and possibly override just those which they need to.
*/
class StreamWrapper : Stream
{
_stream

/**
Constructor.

\param[s] is the stream object to be wrapped.
*/
this(s: Stream)
{
:_stream = s
super()
}

/**
These all simply pass through functionality to the wrapped stream object.
*/
function read(m, off, size) = :_stream.read(m, off, size)
function write(m, off, size) = :_stream.write(m, off, size) /// ditto
function seek(off, where) = :_stream.seek(off, where) /// ditto
function flush() = :_stream.flush() /// ditto
function close() = :_stream.close() /// ditto
function isOpen() = :_stream.isOpen() /// ditto
function readable() = :_stream.readable() /// ditto
function writable() = :_stream.writable() /// ditto
function seekable() = :_stream.seekable() /// ditto

/**
Gets the stream that this instance wraps.

\returns the same stream object that was passed to the constructor.
*/
function getWrappedStream() = :_stream
}

/**
A kind of stream wrapper class that adds a simple interface for reading and writing binary data.

Because it's a stream wrapper, the basic stream interface can still be used on it and the functionality will be passed through
to the wrapped stream.
*/
class BinaryStream : StreamWrapper
{
_rwBuf
_strBuf

/**
Constructor.

\param[s] is the stream to be wrapped.
*/
this(s: Stream)
{
super(s)
:_rwBuf = memblock.new(8)
:_strBuf = memblock.new(0)
}

/**
These all read a single integer or floating-point value of the given type and size.

Note that because Croc's \tt{int} type is a signed 64-bit integer, \tt{readUInt64} will return negative numbers for those
that exceed 2\sup{63} - 1. It exists for completeness.

\returns an \tt{int} or \tt{float} representing the value read.
\throws[EOFException] if end-of-file was reached.
*/
function readInt8() { :_stream.readExact(:_rwBuf, 0, 1); return :_rwBuf.readInt8(0) }
function readInt16() { :_stream.readExact(:_rwBuf, 0, 2); return :_rwBuf.readInt16(0) } /// ditto
function readInt32() { :_stream.readExact(:_rwBuf, 0, 4); return :_rwBuf.readInt32(0) } /// ditto
function readInt64() { :_stream.readExact(:_rwBuf, 0, 8); return :_rwBuf.readInt64(0) } /// ditto
function readUInt8() { :_stream.readExact(:_rwBuf, 0, 1); return :_rwBuf.readUInt8(0) } /// ditto
function readUInt16() { :_stream.readExact(:_rwBuf, 0, 2); return :_rwBuf.readUInt16(0) } /// ditto
function readUInt32() { :_stream.readExact(:_rwBuf, 0, 4); return :_rwBuf.readUInt32(0) } /// ditto
function readUInt64() { :_stream.readExact(:_rwBuf, 0, 8); return :_rwBuf.readUInt64(0) } /// ditto
function readFloat32() { :_stream.readExact(:_rwBuf, 0, 4); return :_rwBuf.readFloat32(0) } /// ditto
function readFloat64() { :_stream.readExact(:_rwBuf, 0, 8); return :_rwBuf.readFloat64(0) } /// ditto

/**
Reads a binary representation of a \tt{string} object. Should only be used as the inverse to \link{writeString}.

\returns a \tt{string} representing the value read.
\throws[EOFException] if end-of-file was reached.
*/
function readString()
{
local len = :readUInt64()
#:_strBuf = len
:stream.readExact(:_strBuf)
return text.fromRawUnicode(:_strBuf)
}

/**
Reads a given number of \b{ASCII} characters and returns them as a string.

This is particularly useful for chunk identifiers in RIFF-type files and "magic numbers", though it can have other uses as well.

\param[n] is the number of bytes to read.

\returns a \tt{string} representing the characters read.

\throws[exceptions.RangeException] if \tt{n < 1}.
\throws[EOFException] if end-of-file was reached.
*/
function readChars(n: int)
{
if(n < 1)
throw RangeException("Invalid number of characters ({})".format(n))

#:_strBuf = n
:stream.readExact(:_strBuf)
return text.fromRawAscii(:_strBuf)
}

/**
These all write a single integer or floating-point value of the given type and size.

\param[x] is the value to write.
\returns \tt{this}.
\throws[EOFException] if end-of-file was reached.
*/
function writeInt8(x: int) { :_rwbuf.writeInt8(0, x); :_stream.writeExact(:_rwBuf, 0, 1); return this }
function writeInt16(x: int) { :_rwbuf.writeInt16(0, x); :_stream.writeExact(:_rwBuf, 0, 2); return this }
function writeInt32(x: int) { :_rwbuf.writeInt32(0, x); :_stream.writeExact(:_rwBuf, 0, 4); return this }
function writeInt64(x: int) { :_rwbuf.writeInt64(0, x); :_stream.writeExact(:_rwBuf, 0, 8); return this }
function writeUInt8(x: int) { :_rwbuf.writeUInt8(0, x); :_stream.writeExact(:_rwBuf, 0, 1); return this }
function writeUInt16(x: int) { :_rwbuf.writeUInt16(0, x); :_stream.writeExact(:_rwBuf, 0, 2); return this }
function writeUInt32(x: int) { :_rwbuf.writeUInt32(0, x); :_stream.writeExact(:_rwBuf, 0, 4); return this }
function writeUInt64(x: int) { :_rwbuf.writeUInt64(0, x); :_stream.writeExact(:_rwBuf, 0, 8); return this }
function writeFloat32(x: float) { :_rwbuf.writeFloat32(0, x); :_stream.writeExact(:_rwBuf, 0, 4); return this }
function writeFloat64(x: float) { :_rwbuf.writeFloat64(0, x); :_stream.writeExact(:_rwBuf, 0, 8); return this }

/**
Writes a binary representation of the given string. To read this binary representation back again, use \link{readString}.

\param[x] is the string to write.
\returns \tt{this}.
\throws[EOFException] if end-of-file was reached.
*/
function writeString(x: string)
{
text.toRawUnicode(x, 8, :_strBuf)
:writeUInt64(#:_strBuf)
:stream.writeExact(:_strBuf)
return this
}

/**
Writes the given string, which must be ASCII only, as a raw sequence of byte-sized characters.

This is particularly useful for chunk identifiers in RIFF-type files and "magic numbers", though it can have other uses
as well.

\param[x] is the string containing the characters to be written. It must be ASCII.
\returns \tt{this}.
\throws[exceptions.ValueException] if \tt{x} is not ASCII.
\throws[EOFException] if end-of-file was reached.
*/
function writeChars(x: string)
{
if(!ascii.isAscii(x))
throw ValueException("Can only write ASCII strings as raw characters")

text.toRawAscii(x, :_strBuf)
:stream.writeExact(:_strBuf)
return this
}
}

/**
A stream wrapper that adds input buffering. Note that this class only allows reading and seeking; writing is unsupported.

This stream adds a transparent buffering scheme when reading data. Seeking is also allowed and will work correctly even
if data is buffered.
*/
class BufferedInStream : StreamWrapper
{
_buf
_bufPos = 0
_bound = 0

/**
Constructor.

\param[s] is the stream to be wrapped.
\param[bufSize] is the size of the memory buffer. Defaults to 4KB. Its size is clamped to a minimum of 128 bytes, and
there is no upper limit.
*/
this(s: @InStream, bufSize: int = 4096)
{
super(s)
:_buf = memblock.new(clamp(bufSize, 128, intMax))
}

/**
Regardless of whether or not the underlying stream is writable, this class is not. Erratic behavior can result if you try
to write to a stream that is wrapped by this class.

\returns false.
*/
function writable() =
false

/**
Implementation of the \tt{read} method. It works exactly like the normal \tt{read} method, performing buffering transparently.

The call signature and return values are the same as \link{Stream.read}.
*/
function read(m: memblock, offset: int = 0, size: int = #m - offset)
{
checkRWParams(m, offset, size)
local remaining = size

while(remaining > 0)
{
local buffered = :_bound - :_bufPos

if(buffered == 0)
{
buffered = :_readMore()

if(buffered == 0)
break
}

local num = min(buffered, remaining)
m.rawCopy(offset, :_buf, :_bufPos, num)
:_bufPos += num
offset += num
remaining -= num
}

return size - remaining
}

/**
Implementation of the \tt{seek} method. It works exactly like the normal \tt{seek} method, and will seek properly even if
data has been buffered.

Seeking will clear the data buffer. The call signature and return values are the same as \link{Stream.seek}.
*/
function seek(this: @SeekStream, offset: int, where: char)
{
if(where == 'c')
offset -= :_bound - :_bufPos

:_bufPos, :_bound = 0, 0
return :_stream.seek(offset, where)
}

function _readMore()
{
assert((:_bound - :_bufPos) == 0)
:_bufPos = 0
:_bound = :_stream.read(:_buf)
return :_bound
}
}

/**
A stream wrapper that adds output buffering. Note that this class only allows writing and seeking; reading is unsupported.

This stream adds a transparent buffering scheme when writing data. Seeking is also allowed and will work correctly even
if data is buffered.
*/
class BufferedOutStream : StreamWrapper
{
_buf
_bufPos = 0

/**
Constructor.

\param[s] is the stream to be wrapped.
\param[bufSize] is the size of the memory buffer. Defaults to 4KB. Its size is clamped to a minimum of 128 bytes, and
there is no upper limit.
*/
this(s: @OutStream, bufSize: int = 4096)
{
super(s)
:_buf = memblock.new(clamp(bufSize, 128, intMax))
}

/**
Regardless of whether or not the underlying stream is readable, this class is not. Erratic behavior can result if you try
to read from a stream that is wrapped by this class.

\returns false.
*/
function readable() =
false

/**
Implementation of the \tt{write} method. It works exactly like the normal \tt{write} method, performing buffering transparently.

The call signature and return values are the same as \link{Stream.write}.
*/
function write(m: memblock, offset: int = 0, size: int = #m - offset)
{
checkRWParams(m, offset, size)
local remaining = size

while(remaining > 0)
{
local spaceLeft = #:_buf - :_bufPos

if(spaceLeft == 0)
{
:flush()
spaceLeft = #:_buf
}

local num = min(spaceLeft, remaining)
:_buf.rawCopy(:_bufPos, m, offset, num)
:_bufPos += num
offset += num
remaining -= num
}

return size - remaining
}

/**
Implementation of the \tt{seek} method. It works exactly like the normal \tt{seek} method, and will seek properly even if
data has been buffered.

Seeking will flush the data buffer. The call signature and return values are the same as \link{Stream.seek}.
*/
function seek(offset: int, where: char)
{
if(where == 'c')
offset -= :_bufPos

if(:_bufPos > 0)
:flush()

return :_stream.seek(offset, where)
}

/**
Implementation of the \tt{flush} method. This writes any buffered data to the stream. If no data is buffered, does nothing.

\throws[EOFException] if end-of-file is reached.
*/
function flush()
{
if(:_bufPos > 0)
{
:_stream.write(:_buf, 0, :_bufPos)
:_bufPos = 0
:_stream.flush()
}
}

/**
Implementation of the \tt{close} method. Simply flushes the buffer and then calls \tt{close} on the underlying stream.
*/
function close()
{
:_flush()
:_stream.close()
}
}
Something went wrong with that request. Please try again.