First the intended usage scenario: this module has been conceived to shorten ids, URLs etc., like the URL shortening services do (then it can be extended to some other mildly interesting uses: please see the "COOKBOOK" section below).

Then a bit of theory: an id is (or can anyway be mapped to) just a number, therefore it can be represented in any base. The longer is the alphabet of the base, the shorter the number representation will be (in terms of symbols of the said alphabet). This module converts any non-negative decimal integer (including Math::BigInt-compatible objects) to any given base/alphabet and vice versa, thus giving the shortest possible representation for the original number/id (provided that we are dealing with a collision-free transformation of random, non-skewed data).

The suggested workflow to shorten your ids is therefore the following:

when storing an item in your data store, generate a decimal id for it (for example through the SEQUENCE field type offered by many DBMSs);

shorten the said decimal id through the "to_base" method explained below;

publish the shortened id rather than the (longer) original decimal id.

When receiving a request for a certain item through its corresponding shortened id you've published:

obtain the corresponding original decimal id through the "to_dec" method explained below;

retrieve the requested item in your data store through its original decimal id you've obtained at the previous step;

serve the requested item.

Of course one can also save the shortened id along with the item in the data store, thus saving the to_dec conversion at the step 1 above (using the shortened id rather than the decimal one in the subsequent step 2).

Through the fast native unary increment/decrement offered by the "next" and "prev" methods, it is even possible to skip the decimal ids generation and the conversion steps altogether.

A couple of similar modules were already present on CPAN, but for one reason or another I did not find them completely satisfactory: for a detailed explanation, please see the "COMPARISON" section below.

This is the constructor method, which initializes and returns the converter object. It requires an alphabet, that is the set of symbols to represent the converted numbers (the size of the base is the number of symbols of the provided alphabet).

An exception is thrown if no alphabet is passed to new.

The alphabet can be passed as a list or as a listref of characters, or packed into a string (in which case the alphabet is obtained by splitting the string into its individual characters).

For example the following three invocations return exactly the same object:

As a single symbol alphabet is not admissible, when new is called with a single (string) parameter, it is interpreted as a string containing the whole alphabet and not as a list containing a single (multichar) symbol. In other words, if you want to pass the alphabet as a list, it must contain at least two elements.

The alphabet can't contain symbols longer than one character, otherwise an exception is thrown. Note that this can happen only when the alphabet is passed as a list or a listref, since when a (single) string is given to new, the alphabet is obtained by splitting the string into its individual characters (and the possible duplicate characters are removed), so no multichar symbols are ever created in this case:

# Error: the last symbol in the provided alphabet (as a list) is two characters long
Number::AnyBase->new( qw/z z z aa/ );
# This is instead correct since the alphabet will be: 'z', 'a'
Number::AnyBase->new( 'zzzaa' );

This is the method which transforms the given decimal number into its representation in the new base, as shown in the "SYNOPSIS" above.

It works only on decimal non-negative integers (including 0). For speed reasons, no check is performed on the given number: in case it is illegal, the behavior is currently indeterminate.

It works transparently also on Math::BigInt-compatible objects (that is, any object which overloads the arithmetic operators like Math::BigInt does): just pass any such big number and you will get the correct result:

This permits to freely choose any Math::BigIntoption (the accuracy, as shown above, or the backend library etc.), or to use any other compatible class, such as, for example, Math::GMP or Math::Int128 (in this latter case, if the number size permits its use).

This is the method which converts the transformed number (or rather string) back to its decimal representation, as exemplified in the "SYNOPSIS" above.

For speed reasons, no check is performed on the given string, which could be inconsistent (for example because it contains characters not present in the current alphabet): in this case the behavior is currently indeterminate.

It accepts a second optional parameter, which should be a Math::BigInt-compatible object (it does not matter if it is initialized or not), which tells to_base that a bignum result is requested. It is necessary only when the result is too large to be held by a native perl integer (though, other than slowing down the conversion, it does not cause any harm, so in case of doubt it can be used anyway).

The passed bignum object is then used for the internal calculations so, though unusual, this interface permits to have the maximum flexibility, as it completely decouples the bignum library, allowing the user to freely choose any Math::BigIntoption as well as any (faster) Math::BigInt-compatible alternative (such as Math::GMP, or Math::Int128 when permitted by the number size):

This example shows how the bytes alphabet can be used to effectively compress random data, when expressed in a shorter alphabet (the DNA alphabet in this case).

If the data are sufficiently randomized (i.e. not skewed), this technique easily beats most general purpose compression algorithms.

As shown below, in this particular case the conversion to the bytes alphabet produces about a 40% better compression than zip (with default options). Even the conversions to the urisafe and to the printable ascii alphabets offer a better compression, and they have the additional advantage that the produced string has only safe characters.

(Though not necessary in this particular case, to avoid any loss of data in the general case, a C symbol has been prepended to the DNA string before the conversion to a decimal: it must be removed once the DNA string is restored from the decimal).

Of course there is nothing magic here: this technique simply leads to a 2-bit representation for the original symbols (being them just 4). For truly random data, this is the best that can be done however (compression algorithms specifically tailored for DNA sequences there exist, but they still rely on some data pattern repetitions to get better results).

In a sense, this example is the opposite of the previous one: this time the target alphabet is shorter than the source one, therefore the resulting string is longer than the original one. There is an advantage however: the resulting string contains only safe characters (while the original string is in general binary), and it can therefore be trasmitted/embedded where binary data would have caused problems.

Working on the whole original string rather than on blocks, the technique shown below easily beats any binary-to-text standard algorithm (the efficiency of which is measured by the shortness of the overhead added to the original data), such as Base64 or Ascii85 (to be fair, the Number::AnyBase ascii alphabet has more than 85 symbols, but that's a Number::AnyBase merit :-)

Also note how, in order to maximize the efficiency, Number::AnyBase lets freely choose the bignum library (in this case the excellent Math::GMP), even when converting (to decimals) from arbitrary alphabets.

(To avoid any loss of data, chr(1) as been prepended to the binary string before the conversion to a decimal: it must be removed once the binary string is restored from the decimal).

The downside is that this technique becomes impractical (both in time and space efficiency) when the string to convert grows. It can however be applied block-by-block, say up to blocks of (few) tens of Kbytes, still producing the best results.

This example is a mix of the previous two: using a longer alphabet, it compresses the original (hexadecimal) UUID, but it keeps also the UUID textual.

Once again it is shown how, in order to maximize the efficiency, Number::AnyBase can freely choose the bignum library to use: in this case the excellent Math::Int128 (which fits perfectly, being an UUID exactly 128-bit long).

This module focuses only on converting numbers from decimals to any base/alphabet and vice versa, therefore it has nothing to do with security, that is, given a number/string and the alphabet it is represented on, the next (through an unary increment) number/string is guessable. If you want your (converted) id sequence not to be guessable, the solution is however simple: just randomize your decimal numbers upfront, leaving large random gaps in the set. Then feed the randomized decimals to this module to have them shortened.

Characters ordering in the given alphabet does matter: if it is desidered that converting a sorted sequence of decimals produces a sorted sequence of strings (when properly padded of course), the characters in the provided alphabet must be sorted as well.

An alphabet with unsorted characters can be used to make the converted numbers somewhat harder to guess.

For maximum speed, as a constructor use fastnew or any of the predefined constructors, resorting to new only when it is necessary to perform the extra checks.

Conversion speed maximization does not require any trick: as long as big numbers are not used, the calculations are performed at the full perl native integers speed.

Big numbers of course slow down the conversions but, as shown above, performances can be fine-tuned, for example by properly setting the Math::BigInt precision and accuracy, by choosing a faster back-end library, or by using Math::GMP directly in place of Math::BigInt (advised). If permitted by the number size, Math::Int128 is an even faster alternative.

As already said, the optimized native unary increment [decrement] provided by next [prev] is over 2x faster than the to_dec/to_base conversion rountrip. However, if a sequence of converted numbers must be generated, and such sequence is large enough so that the first to_dec() call can be amortized, using to_base() (only) is marginally faster than using next:

For the performance claims, please see the benchmark/other_cpan_modules.pl benchmark script included in the distribution. Also note that the conversion speed gaps tend to increase with the numbers size.

vs Math::BaseCalc

Pros

Number::AnyBase is faster: decimal->base conversion is about 2x (100%) faster, base->decimal conversion is about on par, fastnew is about 20% faster than Math::BaseCalc::new.

Base->decimal conversion in Number::AnyBase can return Math::BigInt (or similar) objects upon request, while Math::BaseCalc only returns native perl integers, thus producing wrong results when the decimal number is too large.

Math::BaseCalc::new converts also negative integers, while Number::AnyBase only converts non-negative integers (this feature has been considered not particularly important and therefore traded for speed in Number::AnyBase).

With big integers (60 digits), Number::AnyBase (using Math::GMP) is still faster: over 13x faster in both decimal->base conversion and base->decimal conversion; though much less, it's faster even using Math::BigInt with its pure-perl backend.

Math::BaseConvert has a weird API: first it has a functional interface, which is not ideal for code which has to maintain its internal state. Then, though a custom alphabet can be set (through a state-changing function called dig), every time cnv is called, the target alphabet size must be passed anyway.

Math::BaseConvert doesn't permit to use a bignum library other than Math::BigInt, nor it permits to set any Math::BigInt option.

Math::BaseConvert manages big numbers transparently (but this makes it extremely slow and does not permit to use a library other than Math::BigInt, as already said).

Math::BaseConvert can convert numbers between two arbitrary bases with a single function call.

Math::BaseConvert converts also negative integers.

vs Math::Base::Convert

Pros

With native perl integers, Number::AnyBase is largely faster: something like over 15x faster in decimal->base conversion and over 22x faster in base->decimal conversion (using the Math::Base::Convert object API, which is the recommended one for speed); fastnew is over 70% faster than Math::Base::Convert::new.

With big integers (60 digits), Number::AnyBase (using Math::GMP) is still faster: about 15% faster in decimal->base conversion and about 100% faster in base->decimal conversion.

Though generally better, Math::Base::Convert preserves some of the Math::BaseConvert API shortcomings: to convert numbers bidirectionally between base 10 to/from another given base, two different objects must be istantiated (or the bases must be passed each time through the functional API).

Possible minor glitch: some of the predefined alphabets offered by Math::Base::Convert are not sorted.

Cons

Math::Base::Convert manages big numbers transparently and natively, i.e. without resorting to Math::BigInt or similar modules (but, though not as slow as Math::BaseConvert, this makes Math::Base::Convert massively slow as well, when native perl integers can be used).

On big integers, if Number::AnyBase uses Math::BigInt with its pure-perl engine, Math::Base::Convert is faster: about 11x in decimal->base conversion and about 6x in in base->decimal conversion (as already said, Number::AnyBase can however use Math::GMP and be faster even with big numbers).

Math::Base::Convert can convert numbers between two arbitrary bases with a single function call.

Math::Base::Convert converts also negative integers.

All of the reviewed modules are pure-perled, though the Math::GMP module that Number::AnyBase can (optionally) use to maximize its speed with big numbers it's not. Note however that the Number::AnyBase fast native unary increment/decrement work on arbitrarily big numbers without any external module.