Type::Tiny Tricks #4: Inlined Type Constraints

If ever you're unsure of how a type constraint has been defined, you can examine the string of Perl code used to implement it. For example, does an ArrayRef[Int] accept an empty arrayref?

   my $type = ArrayRef[Int];
   print $type->inline_check('$X');

That will print something like the following. (I've added whitespace for clarity.)

   do {
      ref($X) eq 'ARRAY'
      and do {
         my $ok = 1;
         for my $i (@{$X}) {
            $ok = 0 && last
               unless (defined $i and $i =~ /\A-?[0-9]+\z/)
         };
         $ok
      }
   }

If you don't see something like that, it might be because you have Type::Tiny::XS loaded and Type::Tiny has been able to find a more efficient way to do the same check. Set the PERL_TYPE_TINY_XS environment variable to false and try again.

The code generated might be a little uglier than hand-crafted code would be, but should be reasonably efficient, and should at least give you an idea how the check has been implemented.

Not all type constraints can be inlined. (All the built-in ones can.) Those than cannot be inlined will throw an exception if you try. Types which can be inlined generally lead to faster code being injected into Moose/Moo constructors, accessors, and so on. So it is worth checking that your type constraints may be inlined.

See Type::Tiny::Manual::Optimization for more information on inlining your type constraints.

Leave a comment

About Toby Inkster

user-pic I'm tobyink on CPAN, IRC and PerlMonks.