This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Some tests for [perl #112244]
[perl5.git] / t / io / crlf.t
CommitLineData
d3db65ff
NIS
1#!./perl -w
2
3BEGIN {
4 chdir 't' if -d 't';
5 @INC = qw(. ../lib);
e05e9c3d
NC
6 require "test.pl";
7 skip_all_without_perlio();
d3db65ff
NIS
8}
9
10use Config;
11
d3db65ff 12
62a28c97 13my $file = tempfile();
d3db65ff 14
f10c05c1
KW
15my $ungetc_count = 8200; # Somewhat over the likely buffer size
16
e05e9c3d 17{
f10c05c1 18 plan(tests => 16 + 2 * $ungetc_count);
14b1a0c4
RGS
19 ok(open(FOO,">:crlf",$file));
20 ok(print FOO 'a'.((('a' x 14).qq{\n}) x 2000) || close(FOO));
21 ok(open(FOO,"<:crlf",$file));
887ede57 22
14b1a0c4
RGS
23 my $text;
24 { local $/; $text = <FOO> }
25 is(count_chars($text, "\015\012"), 0);
26 is(count_chars($text, "\n"), 2000);
887ede57 27
14b1a0c4
RGS
28 binmode(FOO);
29 seek(FOO,0,0);
30 { local $/; $text = <FOO> }
31 is(count_chars($text, "\015\012"), 2000);
887ede57 32
14b1a0c4
RGS
33 SKIP:
34 {
bd1869dc 35 skip_if_miniperl("miniperl can't rely on loading PerlIO::scalar");
14b1a0c4
RGS
36 skip("no PerlIO::scalar") unless $Config{extensions} =~ m!\bPerlIO/scalar\b!;
37 require PerlIO::scalar;
38 my $fcontents = join "", map {"$_\015\012"} "a".."zzz";
39 open my $fh, "<:crlf", \$fcontents;
40 local $/ = "xxx";
41 local $_ = <$fh>;
42 my $pos = tell $fh; # pos must be behind "xxx", before "\nxxy\n"
43 seek $fh, $pos, 0;
44 $/ = "\n";
45 $s = <$fh>.<$fh>;
bd1869dc 46 is($s, "\nxxy\n");
f10c05c1
KW
47
48 for my $i (0 .. $ungetc_count - 1) {
49 my $j = $i % 256;
50 is($fh->ungetc($j), $j, "ungetc of $j returns itself");
51 }
52
53 for (my $i = $ungetc_count - 1; $i >= 0; $i--) {
54 my $j = $i % 256;
55 is(ord($fh->getc()), $j, "getc gets back $j");
56 }
14b1a0c4 57 }
e949e37c 58
14b1a0c4 59 ok(close(FOO));
8229d19f 60
14b1a0c4
RGS
61 # binmode :crlf should not cumulate.
62 # Try it first once and then twice so that even UNIXy boxes
63 # get to exercise this, for DOSish boxes even once is enough.
64 # Try also pushing :utf8 first so that there are other layers
65 # in between (this should not matter: CRLF layers still should
66 # not accumulate).
67 for my $utf8 ('', ':utf8') {
68 for my $binmode (1..2) {
69 open(FOO, ">$file");
70 # require PerlIO; print PerlIO::get_layers(FOO), "\n";
71 binmode(FOO, "$utf8:crlf") for 1..$binmode;
72 # require PerlIO; print PerlIO::get_layers(FOO), "\n";
73 print FOO "Hello\n";
74 close FOO;
75 open(FOO, "<$file");
76 binmode(FOO);
77 my $foo = scalar <FOO>;
78 close FOO;
79 print join(" ", "#", map { sprintf("%02x", $_) } unpack("C*", $foo)),
80 "\n";
bd1869dc
NC
81 like($foo, qr/\x0d\x0a$/);
82 unlike($foo, qr/\x0d\x0d/);
14b1a0c4
RGS
83 }
84 }
d3db65ff 85}
d3db65ff 86
887ede57 87sub count_chars {
14b1a0c4
RGS
88 my($text, $chars) = @_;
89 my $seen = 0;
90 $seen++ while $text =~ /$chars/g;
91 return $seen;
887ede57 92}