diff --git a/spec/std/io/null_spec.cr b/spec/std/io/null_spec.cr new file mode 100644 index 000000000000..ef5e43b2e09f --- /dev/null +++ b/spec/std/io/null_spec.cr @@ -0,0 +1,16 @@ +require "spec" + +describe IO::Null do + it "#read" do + slice = Bytes.new(10, 1_u8) + io = IO::Null.new + + io.read(slice).should eq(0) + slice.each { |byte| byte.should eq(1_u8) } + end + + it "#write" do + io = IO::Null.new + io.write Bytes.new(10) + end +end diff --git a/src/io/null.cr b/src/io/null.cr new file mode 100644 index 000000000000..52f54c43eaed --- /dev/null +++ b/src/io/null.cr @@ -0,0 +1,17 @@ +# An IO object that does nothing, yet always succeeds and never fails. +# +# Any attempt to read results in end-of-file (EOF). Any data written is +# immediately discarded. +# +# Can be used in place of another IO when there is nothing to read, or when the +# output can be discarded. +class IO::Null < IO + # Always returns 0 (reached EOF). + def read(slice : Bytes) + 0 + end + + # Returns immediately (discards *slice*). + def write(slice : Bytes) : Nil + end +end