From 3f61b773e7e430d0264847f8058e499790408469 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig <aborenszweig@manas.com.ar> Date: Sat, 15 Mar 2014 12:11:38 -0300 Subject: [PATCH] Added File#size and File#cmp --- spec/std/file_spec.cr | 19 +++++++++++++++++++ src/file.cr | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/spec/std/file_spec.cr b/spec/std/file_spec.cr index 7caf379f24..aaa4b52645 100755 --- a/spec/std/file_spec.cr +++ b/spec/std/file_spec.cr @@ -107,4 +107,23 @@ describe "File" do rescue Errno end end + + describe "size" do + assert { File.size("#{__DIR__}/data/test_file.txt").should eq(240) } + assert do + File.open("#{__DIR__}/data/test_file.txt", "r") do |file| + file.size.should eq(240) + end + end + end + + describe "cmp" do + it "compares two equal files" do + File.cmp("#{__DIR__}/data/test_file.txt", "#{__DIR__}/data/test_file.txt").should be_true + end + + it "compares two different files" do + File.cmp("#{__DIR__}/data/test_file.txt", "#{__DIR__}/data/test_file.ini").should be_false + end + end end diff --git a/src/file.cr b/src/file.cr index 0b66c5cc3a..0b4c43a51f 100644 --- a/src/file.cr +++ b/src/file.cr @@ -218,6 +218,38 @@ class File end end.compact.join('/') end + + def self.size(filename) + stat(filename).size + end + + def size + stat.size + end + + def self.cmp(filename1, filename2) + return false unless size(filename1) == size(filename2) + + File.open(filename1, "rb") do |file1| + File.open(filename2, "rb") do |file2| + compare_stream(file1, file2) + end + end + end + + def self.compare_stream(stream1, stream2) + buf1 :: UInt8[1024] + buf2 :: UInt8[1024] + + while true + read1 = stream1.read(buf1.buffer, 1024) + read2 = stream2.read(buf2.buffer, 1024) + + return false if read1 != read2 + return false if !buf1.buffer.memcmp(buf2.buffer, read1) + return true if read1 == 0 + end + end end def system2(command) -- GitLab