Project

General

Profile

Bug #9847 ยป strbug.rb

Feldmarschal (Kenneth Guerin), 05/17/2014 06:04 PM

 
1
#!/usr/bin/env ruby
2

    
3
####	This script tests for a bug in File.read where 
4
####	supplying a buffer to File.read inhibits the
5
####	creation of new strings.  This behavior is dependent
6
####	on the size of the string due to Ruby's internal
7
####	optimization on short (<24 bytes) strings.
8

    
9
def cache_display(cache)
10
	##  Display the Cache contents.
11
	puts "  - Cache Size: #{cache.length}"
12
	cache.length.times { |i| puts "    - Size: #{cache[i].length} --> Contents: [#{cache[i][0,4]}...]" }
13
end
14

    
15
def slot_test(slotsz)
16

    
17
	puts "Slot Test: (slotsz=#{slotsz})"
18

    
19
	filename = "strbug-#{slotsz}.dat"
20

    
21
	##	Write 13 strings of size SLOTSZ to strbug.dat
22
	##  The strings values are "AAA..", "BBB..", etc.
23
	##  There are no newlines.  This file mimics a record-
24
	##	based structure.
25
	File.open(filename, "w") do |io|
26
		base = "A"
27
		13.times do
28
			io.write(base * slotsz)
29
			base.succ!
30
		end
31
	end
32

    
33
	##  First Test: Read the Contents of the strbug file
34
	##	using File.read(slotsz).  A unique string will be
35
	##  returned on each successful read.
36

    
37
	puts "- File.read(slotsz) Test:"
38
	cache = Array.new     # Collect the unique strings
39
	buffer = String.new   # Redundant due to io.read action
40
	File.open(filename, "r") do |io|
41
		done = false
42
		until done
43
			buffer = io.read(slotsz)
44
			if buffer.nil?
45
				done = true
46
				puts "  > Null buffer" if ! io.eof?
47
			elsif buffer.length != slotsz
48
				done = true
49
				puts "  > Not enough data"
50
			else
51
				cache << buffer
52
			end
53
		end
54
	end
55

    
56
	##  Display the Cache contents.
57
	cache_display(cache)
58

    
59
	##  First Test: Read the Contents of the strbug file
60
	##	using File.read(slotsz).  A unique string will be
61
	##  returned on each successful read.
62

    
63
	puts "- File.read(slotsz, buffer) Test:"
64
	cache = Array.new
65
	buffer = String.new   # Redundant due to io.read action?
66
	File.open(filename, "r") do |io|
67
		while ! io.read(slotsz, buffer).nil?
68
			cache << String.new(buffer)    # Collect unique strings based on each read
69
		end
70
	end
71

    
72
	##  Display the Cache contents.
73
	cache_display(cache)
74

    
75
	puts ""
76
end
77

    
78
##  Maine.  (Yeah, I'm a quirky C programmer at heart.)
79

    
80
[ 23, 24 ].each { |slotsz| slot_test(slotsz) }