chiark / gitweb /
TOML::Tiny::Faithful: New module
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Mon, 4 May 2020 00:32:43 +0000 (01:32 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Wed, 6 May 2020 00:18:28 +0000 (01:18 +0100)
cpanfile
lib/TOML/Tiny/Faithful.pm [new file with mode: 0644]

index ee63b90306e9b9cd4f3336e5c842004ae973b3cf..414a2127076a47e48bc3e0c461a80f3b6e1987bc 100644 (file)
--- a/cpanfile
+++ b/cpanfile
@@ -10,6 +10,7 @@ recommends 'Types::Serialiser' => 0;
 on test => sub{
   requires 'Data::Dumper'              => '0';
   requires 'DateTime::Format::RFC3339' => '0';
+  requires 'Types::Serialiser'         => '0';
   requires 'Math::BigInt'              => '>= 1.999718';
   requires 'TOML::Parser'              => '0';
   requires 'Test2::V0'                 => '0';
diff --git a/lib/TOML/Tiny/Faithful.pm b/lib/TOML/Tiny/Faithful.pm
new file mode 100644 (file)
index 0000000..5851200
--- /dev/null
@@ -0,0 +1,82 @@
+
+package TOML::Tiny::Faithful;
+use parent TOML::Tiny;
+use DateTime::Format::RFC3339;
+
+use DateTime;
+use Types::Serialiser; # ensures that Parser DTRT with booleans
+
+our @EXPORT = qw(
+  from_toml
+  to_toml
+);
+
+sub _options {
+  inflate_datetime => sub {
+    DateTime::Format::RFC3339->parse_datetime(shift);
+  },
+  inflate_integer => sub { 
+    use bignum;
+    my $s = shift;
+    $s =~ m/^0o/
+       ? Math::BigInt->from_oct($')
+       : Math::BigInt->new($s);
+  },
+  inflate_float => sub { 0. + shift; },
+  no_string_guessing => 1,
+  datetime_formatter => DateTime::Format::RFC3339->new(),
+}
+
+sub new {
+  my ($class, %param) = @_;
+  bless TOML::Tiny->new(_options(), %param), $class;
+}
+sub from_toml {
+  my $source = shift;
+  TOML::Tiny::from_toml($source, _options(), @_);
+}
+sub to_toml {
+  my $source = shift;
+  TOML::Tiny::to_toml($source, _options(), @_);
+}
+
+1;
+
+=head1 SYNOPSIS
+
+  use TOML::Tiny::Faithful qw(from_toml to_toml);
+
+  binmode STDIN,  ':encoding(UTF-8)';
+  binmode STDOUT, ':encoding(UTF-8)';
+
+  # Decoding TOML
+  my $toml = do{ local $/; <STDIN> };
+  my ($parsed, $error) = from_toml $toml;
+
+  # Encoding TOML
+  say to_toml({
+    stuff => {
+      about => ['other', 'stuff'],
+    },
+  });
+
+  # Object API
+  my $parser = TOML::Tiny::Faithful->new;
+  my $data = $parser->decode($toml);
+  say $parser->encode($data);
+
+
+=head1 DESCRIPTION
+
+C<TOML::Tiny::Faithful> is a trivial wrapper around C<TOML::Tiny>
+which sets C<inflate_integer>, C<inflate_float>, C<inflate_datetime>,
+C<no_string_guessing> and C<datetime_formatter> to try to make the
+TOML output faithful to any input TOML.
+
+=head1 SEE ALSO
+
+=over
+
+=item L<TOML::Tiny>
+
+=back