1=pod
2
3=encoding utf-8
4
5=head1 PURPOSE
6
7An example of parameterized types from L<Type::Tiny::Manual::Libraries>.
8The example uses L<Type::Tiny>, L<Type::Library>, and L<Type::Coercion>,
9and makes use of inlining and parameterization, so is a good canary to
10check everything is working.
11
12=head1 AUTHOR
13
14Toby Inkster E<lt>tobyink@cpan.orgE<gt>.
15
16=head1 COPYRIGHT AND LICENCE
17
18This software is copyright (c) 2019-2021 by Toby Inkster.
19
20This is free software; you can redistribute it and/or modify it under
21the same terms as the Perl 5 programming language system itself.
22
23=cut
24
25use strict;
26use warnings;
27use Test::TypeTiny;
28use Test::More;
29
30BEGIN {
31	package My::Types;
32	use Type::Library -base;
33	use Type::Utils 'extends';
34	BEGIN { extends 'Types::Standard' };
35	__PACKAGE__->add_type(
36		name       => 'MultipleOf',
37		parent     => Int,
38		constraint_generator => sub {
39			my $i = assert_Int(shift);
40			return sub { $_ % $i == 0 };
41		},
42		inline_generator => sub {
43			my $i = shift;
44			return sub {
45				my $varname = pop;
46				return (undef, "($varname % $i == 0)");
47			};
48		},
49		coercion_generator => sub {
50			my $i = $_[2];
51			require Type::Coercion;
52			return Type::Coercion->new(
53				type_coercion_map => [
54					Num, qq{ int($i * int(\$_/$i)) }
55				],
56			);
57		},
58	);
59	__PACKAGE__->make_immutable;
60	$INC{'My/Types.pm'} = __FILE__;
61};
62
63use My::Types 'MultipleOf';
64
65my $MultipleOfThree = MultipleOf->of(3);
66
67should_pass(0, $MultipleOfThree);
68should_fail(1, $MultipleOfThree);
69should_fail(2, $MultipleOfThree);
70should_pass(3, $MultipleOfThree);
71should_fail(4, $MultipleOfThree);
72should_fail(5, $MultipleOfThree);
73should_pass(6, $MultipleOfThree);
74should_fail(7, $MultipleOfThree);
75should_fail(-1, $MultipleOfThree);
76should_pass(-3, $MultipleOfThree);
77should_fail(0.1, $MultipleOfThree);
78should_fail([], $MultipleOfThree);
79should_fail(undef, $MultipleOfThree);
80
81subtest 'coercion' => sub {
82	is($MultipleOfThree->coerce(0), 0);
83	is($MultipleOfThree->coerce(1), 0);
84	is($MultipleOfThree->coerce(2), 0);
85	is($MultipleOfThree->coerce(3), 3);
86	is($MultipleOfThree->coerce(4), 3);
87	is($MultipleOfThree->coerce(5), 3);
88	is($MultipleOfThree->coerce(6), 6);
89	is($MultipleOfThree->coerce(7), 6);
90	is($MultipleOfThree->coerce(8), 6);
91	is($MultipleOfThree->coerce(8.9), 6);
92};
93
94#diag( $MultipleOfThree->inline_check('$VALUE') );
95
96done_testing;
97
98