chiark / gitweb /
Doc updates
[nailing-cargo.git] / lib / TOML / Tiny.pm
1 package TOML::Tiny;
2 # ABSTRACT: a minimal, pure perl TOML parser and serializer
3
4 use strict;
5 use warnings;
6 no warnings qw(experimental);
7 use v5.18;
8
9 use TOML::Tiny::Parser;
10 use TOML::Tiny::Writer;
11
12 use parent 'Exporter';
13
14 our @EXPORT = qw(
15   from_toml
16   to_toml
17 );
18
19 #-------------------------------------------------------------------------------
20 # TOML module compatibility
21 #-------------------------------------------------------------------------------
22 sub from_toml {
23   my $source = shift;
24   my $parser = TOML::Tiny::Parser->new(@_);
25   my $toml = eval{ $parser->parse($source) };
26   if (wantarray) {
27     return ($toml, $@);
28   } else {
29     die $@ if $@;
30     return $toml;
31   }
32 }
33
34 sub to_toml {
35   goto \&TOML::Tiny::Writer::to_toml;
36 }
37
38 #-------------------------------------------------------------------------------
39 # Object API
40 #-------------------------------------------------------------------------------
41 sub new {
42   my ($class, %param) = @_;
43   bless{ %param, parser => TOML::Tiny::Parser->new(%param) }, $class;
44 }
45
46 sub encode {
47   my ($self, $source) = @_;
48   $self->{parser}->parse;
49 }
50
51 sub decode {
52   my ($self, $data) = @_;
53   TOML::Tiny::Writer::to_toml($data,
54     strict_arrays => $self->{strict_arrays},
55   );
56 }
57
58 #-------------------------------------------------------------------------------
59 # For compatibility with TOML::from_toml's use of $TOML::Parser
60 #-------------------------------------------------------------------------------
61 sub parse {
62   goto \&encode;
63 }
64
65 1;
66
67 =head1 SYNOPSIS
68
69   use TOML::Tiny qw(from_toml to_toml);
70
71   binmode STDIN,  ':encoding(UTF-8)';
72   binmode STDOUT, ':encoding(UTF-8)';
73
74   # Decoding TOML
75   my $toml = do{ local $/; <STDIN> };
76   my ($parsed, $error) = from_toml $toml;
77
78   # Encoding TOML
79   say to_toml({
80     stuff => {
81       about => ['other', 'stuff'],
82     },
83   });
84
85   # Object API
86   my $parser = TOML::Tiny->new;
87   my $data = $parser->decode($toml);
88   say $parser->encode($data);
89
90
91 =head1 DESCRIPTION
92
93 C<TOML::Tiny> implements a pure-perl parser and generator for the
94 L<TOML|https://github.com/toml-lang/toml> data format. It conforms to TOML v5
95 (with a few caveats; see L</strict_arrays>) with support for more recent
96 changes in pursuit of v6.
97
98 C<TOML::Tiny> strives to maintain an interface compatible to the L<TOML> and
99 L<TOML::Parser> modules, and could even be used to override C<$TOML::Parser>:
100
101   use TOML;
102   use TOML::Tiny;
103
104   local $TOML::Parser = TOML::Tiny->new(...);
105   say to_toml(...);
106
107
108 =head1 EXPORTS
109
110 C<TOML::Tiny> exports the following to functions for compatibility with the
111 L<TOML> module. See L<TOML/FUNCTIONS>.
112
113 =head2 from_toml
114
115 Parses a string of C<TOML>-formatted source and returns the resulting data
116 structure. Any arguments after the first are passed to L<TOML::Tiny::Parser>'s
117 constructor.
118
119 If there is a syntax error in the C<TOML> source, C<from_toml> will die with
120 an explanation which includes the line number of the error.
121
122   my $result = eval{ from_toml($toml_string) };
123
124 Alternately, this routine may be called in list context, in which case syntax
125 errors will result in returning two values, C<undef> and an error message.
126
127   my ($result, $error) = from_toml($toml_string);
128
129 Homogenous array strictures are enabled by passing C<strict_arrays>:
130
131   # Croaks
132   my $result = from_toml(q{mixed=[1, 2, "three"]})
133
134 Additional arguments may be passed after the toml source string; see L</new>.
135
136 =head2 to_toml
137
138 Encodes a hash ref as a C<TOML>-formatted string.
139
140   my $toml = to_toml({foo => {'bar' => 'bat'}});
141
142   # [foo]
143   # bar="bat"
144
145 Homogenous array strictures are enabled by passing C<strict_arrays>:
146
147   # Croaks
148   my $toml = to_toml({mixed => [1, 2, "three"]}, strict_arrays => 1);
149
150 =head1 OBJECT API
151
152 =head2 new
153
154 =over
155
156 =item inflate_datetime
157
158 By default, C<TOML::Tiny> treats TOML datetimes as strings in the generated
159 data structure. The C<inflate_datetime> parameter allows the caller to provide
160 a routine to intercept those as they are generated:
161
162   use DateTime::Format::RFC3339;
163
164   my $parser = TOML::Tiny->new(
165     inflate_datetime => sub{
166       my $dt_string = shift;
167       return DateTime::Format::RFC3339->parse_datetime($dt_string);
168     },
169   );
170
171 =item inflate_boolean
172
173 By default, boolean values in a C<TOML> document result in a C<1> or C<0>.
174 If L<Types::Serialiser> is installed, they will instead be C<Types::Serialiser::true>
175 or C<Types::Serialiser::false>.
176
177 If you wish to override this, you can provide your own routine to generate values:
178
179   my $parser = TOML::Tiny->new(
180     inflate_boolean => sub{
181       my $bool = shift;
182       if ($bool eq 'true') {
183         return 'The Truth';
184       } else {
185         return 'A Lie';
186       }
187     },
188   );
189
190 =item strict_arrays
191
192 C<TOML v5> specified homogenous arrays. This has since been removed and will no
193 longer be part of the standard as of C<v6> (as of the time of writing; the
194 author of C<TOML> has gone back and forth on the issue, so no guarantees).
195
196 By default, C<TOML::Tiny> is flexible and supports heterogenous arrays. If you
197 wish to require strictly typed arrays (for C<TOML>'s definition of "type",
198 anyway), C<strict_arrays> will produce an error when encountering arrays with
199 heterogenous types.
200
201 =back
202
203 =head2 decode
204
205 Decodes C<TOML> and returns a hash ref. Dies on parse error.
206
207 =head2 encode
208
209 Encodes a perl hash ref as a C<TOML>-formatted string. Dies when encountering
210 an array of mixed types if C<strict_arrays> was set.
211
212 =head2 parse
213
214 Alias for C<encode> to provide compatibility with C<TOML::Parser> when
215 overriding the parser by setting C<$TOML::Parser>.
216
217
218 =head1 DIFFERENCES FROM L<TOML> AND L<TOML::Parser>
219
220 C<TOML::Tiny> differs in a few significant ways from the L<TOML> module,
221 particularly in adding support for newer C<TOML> features and strictness.
222
223 L<TOML> defaults to lax parsing and provides C<strict_mode> to (slightly)
224 tighten things up. C<TOML::Tiny> defaults to (somehwat) stricter parsing, with
225 the exception of permitting heterogenous arrays (illegal in v4 and v5, but
226 permissible in the upcoming v6); optional enforcement of homogenous arrays is
227 supported with C<strict_arrays>.
228
229 C<TOML::Tiny> ignores invalid surrogate pairs within basic and multiline
230 strings (L<TOML> may attempt to decode an invalid pair). Additionally, only
231 those character escapes officially supported by TOML are interpreted as such by
232 C<TOML::Tiny>.
233
234 C<TOML::Tiny> supports stripping initial whitespace and handles lines
235 terminating with a backslash correctly in multilne strings:
236
237   # TOML input
238   x="""
239   foo"""
240
241   y="""\
242      how now \
243        brown \
244   bureaucrat.\
245   """
246
247   # Perl output
248   {x => 'foo', y => 'how now brown bureaucrat.'}
249
250 C<TOML::Tiny> includes support for integers specified in binary, octal or hex
251 as well as the special float values C<inf> and C<nan>.
252
253 =head1 ACKNOWLEDGEMENTS
254
255 Thanks to L<ZipRecruiter|https://www.ziprecruiter.com> for encouraging their
256 employees to contribute back to the open source ecosystem. Without their
257 dedication to quality software development this distribution would not exist.