aboutsummaryrefslogtreecommitdiff
path: root/tcltests/test_bio.tcl
blob: c35977d9c39e6cb9dfce6fe7c1aa9a350abd40c0 (plain)
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
if {[info commands bio] eq ""} {
	return "noimpl"
}
if {[info commands verbose] eq ""} {
	proc verbose {msg} {puts $msg}
}

proc copy_binary_file {infile outfile} {
	set in [open $infile r]
	set out [open $outfile w]
	while {[bio read $in buf 200] > 0} {
		bio write $out $buf
	}
	close $in
	close $out
}

proc copy_binary_file_direct {infile outfile} {
	set in [open $infile r]
	set out [open $outfile w]
	bio copy $in $out
	close $in
	close $out
}

proc copy_file {infile outfile} {
	set in [open $infile r]
	set out [open $outfile w]
	while {1} {
		set buf [read $in 200]
		if {[string length $buf] == 0} {
			break
		}
		puts -nonewline $out $buf
	}
	close $in
	close $out
}

proc copy_binary_file_hex {infile outfile} {
	set in [open $infile r]
	set out [open $outfile w]
	while {[bio read -hex $in buf 200] > 0} {
		bio write -hex $out $buf
	}
	close $in
	close $out
}

proc check_file {message filename} {
	# Does it look OK?
	set rc [catch {exec cmp -s $filename test.bin} error]
	if {$rc != 0} {
		puts "$message ($error)"
		puts "=========================================="
		puts "Did not match: $filename test.bin"
		error failed
	}
	verbose "$message -- ok"
}

# First create a binary file with the chars 0 - 255
set f [open bio.test w]
for {set i 0} {$i < 256} {incr i} {
	puts -nonewline $f [format %c $i]
}
close $f
check_file "Create binary file from std encoding" bio.test

# Now the same using hex mode
set hex ""
for {set i 0} {$i < 256} {incr i} {
	append hex [format %02x $i]
}
set f [open bio.test w]
bio write -hex $f $hex
close $f
check_file "Create binary file from hex encoding" bio.test

copy_binary_file bio.test bio.copy
check_file "Copy binary file with std encoding" bio.copy
copy_binary_file_direct bio.test bio.copy
check_file "Copy binary file with bio copy" bio.copy
copy_binary_file_hex bio.test bio.copy
check_file "Copy binary file with hex encoding" bio.copy
copy_file bio.test bio.copy
check_file "Copy file with stdio" bio.copy
file delete bio.test
file delete bio.copy