Don't fail mysteriously on existing trace file.
[ccan] / ccan / array / test / testLits_generate.pl
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 my $amount = 10;
6 my $maxLen = 509;
7 srand(0);
8
9 my $templateFile = 'testLits.h.template';
10 my $outFile = 'testLits.h';
11
12 open(TF, $templateFile);
13
14 open(OUT, '>'.$outFile);
15 select OUT;
16
17 my $inLoop = 0;
18 my $loopText = '';
19
20 foreach my $line (<TF>) {
21         $line =~ s/\@amount/$amount/g;
22         if (!$inLoop) {
23                 if ($line =~ /\@forEachRandomString/) {
24                         $inLoop = 1;
25                         next;
26                 }
27                 print $line;
28         } elsif ($inLoop == 1) {
29                 if ($line =~ /\@end/) {
30                         $inLoop = 0;
31                         #handle $loopText
32                         for (my $i=0; $i<$amount; $i++) {
33                                 my $str = randomCString($maxLen);
34                                 my $lt = $loopText;
35                                 $lt =~ s/\@i/$i/g;
36                                 $lt =~ s/\@str/\"$str\"/g;
37                                 print "$lt\n";
38                         }
39                         $loopText = '';
40                         next;
41                 }
42                 $loopText .= $line;
43         }
44 }
45
46 close(OUT);
47 close(TF);
48
49 #argument:  maxLen
50 sub randomCString {
51         my $len = int(rand($_[0]+1));
52         my $lastWasHex = 0;
53         my $str = '';
54         
55         for (my $i=0; $i<$len; $i++) {
56                 my $cn = int(rand(255)) + 1;
57                 my $c = chr($cn);
58                 if ($lastWasHex && ($c =~ /[0-9A-Fa-f]/)) {
59                         $lastWasHex = 1;
60                         $str .= sprintf("\\x%02X", $cn);
61                 } elsif ($c =~ /[\t\n\013\f\r]/) {
62                         $lastWasHex = 0;
63                         $c =~ tr/\t\n\013\f\r/tnvfr/;
64                         $str .= '\\'.$c;
65                 } elsif ($cn<32 || $cn>126) {
66                         $lastWasHex = 1;
67                         $str .= sprintf("\\x%02X", $cn);
68                 } else {
69                         $lastWasHex = 0;
70                         if ($c =~ /[\"\\]/) {
71                                 $str .= '\\'.$c;
72                         } else {
73                                 $str .= $c;
74                         }
75                 }
76         }
77         return $str;
78 }