<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Module::Implementation;
{
  $Module::Implementation::VERSION = '0.06';
}

use strict;
use warnings;

use Module::Runtime 0.012 qw( require_module );
use Try::Tiny;

my %Implementation;

sub build_loader_sub {
    my $caller = caller();

    return _build_loader( $caller, @_ );
}

sub _build_loader {
    my $package = shift;
    my %args    = @_;

    my @implementations = @{ $args{implementations} };
    my @symbols = @{ $args{symbols} || [] };

    my $implementation;
    my $env_var = uc $package;
    $env_var =~ s/::/_/g;
    $env_var .= '_IMPLEMENTATION';

    return sub {
        my ( $implementation, $loaded ) = _load_implementation(
            $package,
            $ENV{$env_var},
            \@implementations,
        );

        $Implementation{$package} = $implementation;

        _copy_symbols( $loaded, $package, \@symbols );

        return $loaded;
    };
}

sub implementation_for {
    my $package = shift;

    return $Implementation{$package};
}

sub _load_implementation {
    my $package         = shift;
    my $env_value       = shift;
    my $implementations = shift;

    if ($env_value) {
        die "$env_value is not a valid implementation for $package"
            unless grep { $_ eq $env_value } @{$implementations};

        my $loaded = "${package}::$env_value";

        # Values from the %ENV hash are tainted. We know it's safe to untaint
        # this value because the value was one of our known implementations.
        ($loaded) = $loaded =~ /^(.+)$/;

        try {
            require_module($loaded);
        }
        catch {
            require Carp;
            Carp::croak("Could not load $loaded: $_");
        };

        return ( $env_value, $loaded );
    }
    else {
        my $err;
        for my $possible ( @{$implementations} ) {
            my $load = "${package}::$possible";

            my $ok;
            try {
                require_module($load);
                $ok = 1;
            }
            catch {
                $err .= $_;
            };

            return ( $possible, $load ) if $ok;
        }

        require Carp;
        Carp::croak(
            "Could not find a suitable $package implementation: $err");
    }
}

sub _copy_symbols {
    my $from_package = shift;
    my $to_package   = shift;
    my $symbols      = shift;

    for my $sym ( @{$symbols} ) {
        my $type = $sym =~ s/^([\$\@\%\&amp;\*])// ? $1 : '&amp;';

        my $from = "${from_package}::$sym";
        my $to   = "${to_package}::$sym";

        {
            no strict 'refs';
            no warnings 'once';

            # Copied from Exporter
            *{$to}
                = $type eq '&amp;' ? \&amp;{$from}
                : $type eq '$' ? \${$from}
                : $type eq '@' ? \@{$from}
                : $type eq '%' ? \%{$from}
                : $type eq '*' ? *{$from}
                : die
                "Can't copy symbol from $from_package to $to_package: $type$sym";
        }
    }
}

1;

# ABSTRACT: Loads one of several alternate underlying implementations for a module



=pod

=head1 NAME

Module::Implementation - Loads one of several alternate underlying implementations for a module

=head1 VERSION

version 0.06

=head1 SYNOPSIS

  package Foo::Bar;

  use Module::Implementation;

  BEGIN {
      my $loader = Module::Implementation::build_loader_sub(
          implementations =&gt; [ 'XS',  'PurePerl' ],
          symbols         =&gt; [ 'run', 'check' ],
      );

      $loader-&gt;();
  }

  package Consumer;

  # loads the first viable implementation
  use Foo::Bar;

=head1 DESCRIPTION

This module abstracts out the process of choosing one of several underlying
implementations for a module. This can be used to provide XS and pure Perl
implementations of a module, or it could be used to load an implementation for
a given OS or any other case of needing to provide multiple implementations.

This module is only useful when you know all the implementations ahead of
time. If you want to load arbitrary implementations then you probably want
something like a plugin system, not this module.

=head1 API

This module provides two subroutines, neither of which are exported.

=head2 Module::Implementation::&lt;build_loader_sub(...)

This subroutine takes the following arguments.

=over 4

=item * implementations

This should be an array reference of implementation names. Each name should
correspond to a module in the caller's namespace.

In other words, using the example in the L&lt;/SYNOPSIS&gt;, this module will look
for the C&lt;Foo::Bar::XS&gt; and C&lt;Foo::Bar::PurePerl&gt; modules will be installed

This argument is required.

=item * symbols

A list of symbols to copy from the implementation package to the calling
package.

These can be prefixed with a variable type: C&lt;$&gt;, C&lt;@&gt;, C&lt;%&gt;, C&lt;&amp;&gt;, or
C&lt;*)&gt;. If no prefix is given, the symbol is assumed to be a subroutine.

This argument is optional.

=back

This subroutine I&lt;returns&gt; the implementation loader as a sub reference.

It is up to you to call this loader sub in your code.

I recommend that you I&lt;do not&gt; call this loader in an C&lt;import()&gt; sub. If a
caller explicitly requests no imports, your C&lt;import()&gt; sub will not be run at
all, which can cause weird breakage.

=head2 Module::Implementation::implementation_for($package)

Given a package name, this subroutine returns the implementation that was
loaded for the package. This is not a full package name, just the suffix that
identifies the implementation. For the L&lt;/SYNOPSIS&gt; example, this subroutine
would be called as C&lt;Module::Implementation::implementation_for('Foo::Bar')&gt;,
and it would return "XS" or "PurePerl".

=head1 HOW THE IMPLEMENTATION LOADER WORKS

The implementation loader works like this ...

First, it checks for an C&lt;%ENV&gt; var specifying the implementation to load. The
env var is based on the package name which loads the implementations. The
C&lt;::&gt; package separator is replaced with C&lt;_&gt;, and made entirely
upper-case. Finally, we append "_IMPLEMENTATION" to this name.

So in our L&lt;/SYNOPSIS&gt; example, the corresponding C&lt;%ENV&gt; key would be
C&lt;FOO_BAR_IMPLEMENTATION&gt;.

If this is set, then the loader will B&lt;only&gt; try to load this one
implementation.

If the env var requests an implementation which doesn't match one of the
implementations specified when the loader was created, an error is thrown.

If this one implementation fails to load then loader throws an error. This is
useful for testing. You can request a specific implementation in a test file
by writing something like this:

  BEGIN { $ENV{FOO_BAR_IMPLEMENTATION} = 'XS' }
  use Foo::Bar;

If the environment variable is I&lt;not&gt; set, then the loader simply tries the
implementations originally passed to C&lt;Module::Implementation&gt;. The
implementations are tried in the order in which they were originally passed.

The loader will use the first implementation that loads without an error. It
will copy any requested symbols from this implementation.

If none of the implementations can be loaded, then the loader throws an
exception.

The loader returns the name of the package it loaded.

=head1 AUTHOR

Dave Rolsky &lt;autarch@urth.org&gt;

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2012 by Dave Rolsky.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)

=cut


__END__

</pre></body></html>