From fa1371b2084d2d1ff41a57751fa562a270faba8d Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 4 May 2020 01:32:43 +0100 Subject: [PATCH] TOML::Tiny::Faithful: New module --- cpanfile | 1 + lib/TOML/Tiny/Faithful.pm | 82 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 lib/TOML/Tiny/Faithful.pm diff --git a/cpanfile b/cpanfile index ee63b90..414a212 100644 --- 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 index 0000000..5851200 --- /dev/null +++ b/lib/TOML/Tiny/Faithful.pm @@ -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 $/; }; + 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 is a trivial wrapper around C +which sets C, C, C, +C and C to try to make the +TOML output faithful to any input TOML. + +=head1 SEE ALSO + +=over + +=item L + +=back -- 2.30.2