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