blib/lib/Data/UUID/NCName.pm

filter: Statementstmt 87.6% 199 / 227 Branchbran 44.8% 26 / 58 Conditioncond 57.6% 15 / 26 MC/DCmcdc 16.6% 2 / 12 Subroutinesub 81.8% 36 / 44 Podpod 100% 8 / 8 totaltotal 76.2% 286 / 375 CC 41 SCAR 23.5
CC
41
Cov
77%
from_ncname
32.2
to_ncname
13.5
__ANON__
13.1
CRAP 10.5
↑ Summary
1 package Data::UUID::NCName;
2  
3 3 ▶use 5.012;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use base 'Exporter::Tiny';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use overload;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 3 ▶use MIME::Base32 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use MIME::Base64 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Math::BigInt ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Encode::Base58::BigInt ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 3 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 3 ▶use Type::Params qw(compile multisig);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 3 ▶use Types::Standard qw(slurpy Maybe Any Item Str Int Dict Object Optional);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 3 ▶use Type::Library -base, -declare => qw(Stringable AnyUUID Format Radix Ver);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 3 ▶use Type::Utils -all;
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 0 ▶sub _to_string {
Subroutine _to_string: not called CC=3 SCAR=24.8
22 0 my $x = shift;
23 0 ▶ overload::Method($x, '""') || $x->can('to_string') || $x->can('as_string');
Branch: 1 branch
BranchTrueFalseTotal
overload::Method($x, "\"\"") or $x->can("to_string") or $x->can("as_string") 0 0 0
Condition0%0/3
overload::Method($x, "\"\"") or $x->can("to_string")
l!l&&r!l&&!r
000
MC/DC0%0/2
overload::Method($x, "\"\"") or $x->can("to_string")
overload::Method($x, "\"\"") $x->can("to_string")
Truth table0%0/3
A or B
A= overload::Method($x, "\"\"")B= $x->can("to_string")
ABresult
1X1
011
000
24 }
25  
26 3 my %B58_FWD = do {
27 3 my @flickr = split //,
28 q{123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ};
29 3 my @btc = split //,
30 q{123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz};
31 3 map { $flickr[$_] => $btc[$_] } (0..$#flickr);
32 };
33 3 my %B58_REV = reverse %B58_FWD;
34  
35  
36 2000 ▶sub _to_base58 {
Subroutine _to_base58: called CC=2 SCAR=7.0
37 # if we turn this to a bigint we need to remove the leading nulls first
38 2000 my $str = shift;
39 2000 $str =~ s/\A(\0*)//;
40 2000 ▶ my $null = $1 // '';
Condition50%1/2
$1 // ""
l!l
20000
MC/DC0%0/1
$1 // ""
$1
Truth table50%1/2
A
A= $1
Aresult
11
00
41 # warn unpack 'H*', $str;
42 2000 my $big = Math::BigInt->from_bytes($str);
43 2000 my $b58 = Encode::Base58::BigInt::encode_base58($big);
44 2000 ('1' x length($null)) . join '', map { $B58_FWD{$_} } (split //, $b58);
45 }
46  
47 2000 ▶sub _from_base58 {
Subroutine _from_base58: called CC=1 SCAR=0.0
48 # again we have to remove any leading zero values (1 in base58) or
49 # they will be clobbered when turned into a bigint
50 2000 my ($null, $b58) = ($_[0] =~ /\A(1*)(.*?)\z/);
51 2000 $b58 = join '', map { $B58_REV{$_} } (split //, $b58);
52 2000 my $big = Math::BigInt->new(Encode::Base58::BigInt::decode_base58($b58));
53 2000 ("\0" x length($null)) . $big->to_bytes;
54 }
55  
56 3 declare Stringable, as Object, where \&_to_string;
57  
58 6010 ▶declare AnyUUID, as Str|Stringable, where {
Subroutine __ANON__: called CC=7 SCAR=25.7
59 3 ▶ use bytes;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 6010 ▶ my $x = ref $_ ? _to_string($_)->($_) : $_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 6010 6010
61  
62 6010 ▶ return 1 if length $x == 16;
Branch: 1 branch
BranchTrueFalseTotal
if length $x == 16 0 6010 6010
63  
64 6010 ▶ if (my ($hex) = ($x =~ /^\s*(?i:urn:uuid:)?([0-9A-Fa-f-]{32,})\s*$/sm)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($hex) = $x =~ /^\s*(?i:urn:uuid:)?([0-9A-Fa-f-]{32,})\s*$/dms) 6010 0 6010
65 6010 $hex =~ s/-//g;
66 6010 ▶ return 1 if length $hex == 32;
Branch: 1 branch
BranchTrueFalseTotal
if length $hex == 32 6010 0 6010
67 }
68  
69 0 ▶ if (my ($b64) = ($x =~ m!^\s*([0-9A-Za-z+/_-]=*)\s*$!sm)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($b64) = $x =~ m[^\s*([0-9A-Za-z+/_-]=*)\s*$]dms) 0 0 0
70 0 $b64 =~ tr!-_!+/!;
71 0 ▶ return 1 if 16 == length(MIME::Base64::decode($b64));
Branch: 1 branch
BranchTrueFalseTotal
if 16 == length &MIME::Base64::decode($b64) 0 0 0
72 }
73  
74 0 return;
75 3 };
76  
77 3 enum Format, [qw(str hex b64 bin)];
78 3 enum Radix, [32, 58, 64];
79 3 enum Ver, [0, 1]; # there may be more versions later on
80  
81 =encoding utf8
82  
83 =head1 NAME
84  
85 Data::UUID::NCName - Make valid NCName tokens which are also UUIDs
86  
87 =head1 VERSION
88  
89 Version 0.07
90  
91 =cut
92  
93 3 our $VERSION = '0.07';
94  
95 =head1 SYNOPSIS
96  
97 use Data::UUID::NCName qw(:all);
98  
99 my $uuid = '1ff916f3-6ed7-443a-bef5-f4c85f18cd10';
100 my $ncn = to_ncname($uuid, version => 1);
101 my $ncn32 = to_ncname($uuid, version => 1, radix => 32);
102  
103 # $ncn is now "EH_kW827XQ6719MhfGM0QL".
104 # $ncn32 is "ed74rn43o25b255puzbprrtiql" and case-insensitive.
105  
106 # from Test::More, this will output 'ok':
107 is(from_ncname($ncn, version => 1),
108 $uuid, 'Decoding result matches original');
109  
110 =head1 DESCRIPTION
111  
112 The purpose of this module is to devise an alternative representation
113 of the L<UUID|http://tools.ietf.org/html/rfc4122> which conforms to
114 the constraints of various other identifiers such as NCName, and create an
115 L<isomorphic|http://en.wikipedia.org/wiki/Isomorphism> mapping between
116 them.
117  
118 =head1 FORMAT DEPRECATION NOTICE
119  
120 After careful consideration, I have decided to change the UUID-NCName
121 format in a minor yet incompatible way. In particular, I have moved
122 the quartet containing the
123 L<C<variant>|https://tools.ietf.org/html/rfc4122#section-4.1.1> to the
124 very end of the identifier, whereas it previously was mixed into the
125 middle somewhere.
126  
127 This can be considered an application of L<Postel's
128 Law|https://en.wikipedia.org/wiki/Postel%27s_law>, based on the
129 assumption that these identifiers will be generated through other
130 methods, and potentially naïvely. Like the C<version> field, the
131 C<variant> field has a limited acceptable range of values. If, for
132 example, one were to attempt to generate a conforming identifier by
133 simply generating a random Base32 or Base64 string, it will be
134 difficult to ensure that the C<variant> field will indeed conform when
135 the identifier is converted to a standard UUID. By moving the
136 C<variant> field out to the end of the identifier, everything between
137 the C<version> and C<variant> bookends can be generated randomly
138 without any further consideration, like so:
139  
140 our @B64_ALPHA = ('A'..'Z', 'a'..'z', 0..9, qw(- _));
141  
142 sub make_cheapo_b64_uuid_ncname () {
143 my @vals = map { int rand 64 } (1..20); # generate content
144 push @vals, 8 + int rand 4; # last digit is special
145 'E' . join '', map { $B64_ALPHA[$_] } @vals; # 'E' for UUID V4
146 }
147  
148 # voilà:
149 my $cheap = make_cheapo_b64_uuid_ncname;
150 # EPrakcT1o2arqWSOuIMGSK or something
151  
152 # as expected, we can decode it (version 1, naturally)
153 my $uu = Data::UUID::NCName::from_ncname($cheap, version => 1);
154 # 3eb6a471-3d68-4d9a-aaea-5923ae20c192 - UUID is valid
155  
156 Furthermore, since the default behaviour is to align the bits of the
157 last byte to the size of the encoding symbol, and since the C<variant>
158 bits are masked, a compliant RFC4122 UUID will I<always> end with
159 C<I>, C<J>, C<K>, or C<L>, in I<both> Base32 (case-insensitive) and
160 Base64 variants.
161  
162 Since I have already released this module prior to this format change,
163 I have added a C<version> parameter to both L</to_ncname> and
164 L</from_ncname>. The version currently defaults to C<1>, the new one,
165 but will issue a warning if not explicitly set. Later I will
166 finally remove the warning with C<1> as the default. This should
167 ensure that any code written during the transition produces the
168 correct results.
169  
170 =over 4
171  
172 Unless you have to support identifiers generated from version 0.04 or
173 older, B<you should be running these functions with C<version =E<gt> 1>>.
174  
175 =back
176  
177 =head1 RATIONALE & METHOD
178  
179 The UUID is a generic identifier which is large enough to be globally
180 unique. This makes it useful as a canonical name for data objects in
181 distributed systems, especially those that cross administrative
182 jurisdictions, such as the World-Wide Web. The
183 L<representation|http://tools.ietf.org/html/rfc4122#section-3>,
184 however, of the UUID, precludes it from being used in many places
185 where it would be useful to do so.
186  
187 In particular, there are grammars for many types of identifiers which
188 must not begin with a digit. Others are case-insensitive, or
189 prohibited from containing hyphens (present in both the standard
190 notation and Base64URL), or indeed anything outside of
191 C<^[A-Za-z_][0-9A-Za-z_]*$>.
192  
193 The hexadecimal notation of the UUID has a 5/8 chance of beginning
194 with a digit, Base64 has a 5/32 chance, and Base32 has a 3/16
195 chance. As such, the identifier must be modified in such a way as to
196 guarantee beginning with an alphabetic letter (or underscore C<_>, but some
197 grammars even prohibit that, so we omit it as well).
198  
199 While it is conceivable to simply add a padding character, there are a
200 few considerations which make it more appealing to derive the initial
201 character from the content of the UUID itself:
202  
203 =over 4
204  
205 =item *
206  
207 UUIDs are large (128-bit) identifiers as it is, and it is undesirable
208 to add meaningless syntax to them if we can avoid doing so.
209  
210 =item *
211  
212 128 bits is an inconvenient number for aligning to both Base32 (130)
213 and Base64 (132), though 120 divides cleanly into 5, 6 and 8.
214  
215 =item *
216  
217 The 13th quartet, or higher four bits of the
218 C<time_hi_and_version_field> of the UUID is constant, as it indicates
219 the UUID's version. If we encode this value using the scheme common to
220 both Base64 and Base32, we get values between C<A> and C<P>, with the
221 valid subset between C<B> and C<F>.
222  
223 =back
224  
225 B<Therefore:> extract the UUID's version quartet, shift all subsequent
226 data 4 bits to the left, zero-pad to the octet, encode with either
227 I<base64url> or I<base32>, truncate, and finally prepend the encoded
228 version character. VoilE<agrave>, one token-safe UUID.
229  
230 =head1 APPLICATIONS
231  
232 =over 4
233  
234 =item XML IDs
235  
236 The C<ID> production appears to have been constricted, inadvertently
237 or otherwise, from L<Name|http://www.w3.org/TR/xml11/#NT-Name> in both
238 the XML 1.0 and 1.1 specifications, to
239 L<NCName|http://www.w3.org/TR/xml-names/#NT-NCName> by L<XML Schema
240 Part 2|http://www.w3.org/TR/xmlschema-2/#ID>. This removes the colon
241 character C<:> from the grammar. The net effect is that
242  
243 <foo id="urn:uuid:b07caf81-baae-449d-8a2e-48c0f5fa5538"/>
244  
245 while being a I<well-formed> ID I<and> valid under DTD validation, is
246 I<not> valid per XML Schema Part 2 or anything that uses it
247 (e.g. Relax NG).
248  
249 =item RDF blank node identifiers
250  
251 Blank node identifiers in RDF are intended for serialization, to act
252 as a handle so that multiple RDF statements can refer to the same
253 blank node. The L<RDF abstract syntax
254 specifies|http://www.w3.org/TR/rdf-concepts/#section-URI-Vocabulary>
255 that the validity constraints of blank node identifiers be delegated
256 to the concrete syntax specifications. The L<RDF/XML syntax
257 specification|http://www.w3.org/TR/rdf-syntax-grammar/#rdf-id>
258 lists the blank node identifier as NCName. However, according to
259 L<the Turtle spec|http://www.w3.org/TR/turtle/#BNodes>, this is a
260 valid blank node identifier:
261  
262 _:42df00ec-30a2-431f-be9e-e3a612b325db
263  
264 despite L<an older
265 version|http://www.w3.org/TeamSubmission/turtle/#nodeID> listing a
266 production equivalent to the more conservative NCName. NTriples
267 syntax is L<even more
268 constrained|http://www.w3.org/TR/rdf-testcases/#ntriples>, given as
269 C<^[A-Za-z][0-9A-Za-z]*$>.
270  
271 =item Generated symbols
272  
273 =over 4
274  
275 There are only two hard things in computer science: cache
276 invalidation and naming things [and off-by-one errors].
277  
278 -- Phil Karlton [extension of unknown origin]
279  
280 =back
281  
282 Suppose you wanted to create a L<literate
283 programming|http://en.wikipedia.org/wiki/Literate_programming> system
284 (I do). One of your (my) stipulations is that the symbols get defined
285 in the I<prose>, rather than the I<code>. However, you (I) still want
286 to be able to validate the code's syntax, and potentially even run the
287 code, without having to commit to naming anything. You are (I am) also
288 interested in creating a global map of classes, datatypes and code
289 fragments, which can be operated on and tested in isolation, ported to
290 other languages, or transplanted into the more conventional packages
291 of programs, libraries and frameworks. The Base32 UUID NCName
292 representation should be adequate for placeholder symbols in just
293 about any programming language, save for those which do not permit
294 identifiers as long as 26 characters (which are extremely scarce).
295  
296 =back
297  
298 =head1 EXPORT
299  
300 No subroutines are exported by default. Be sure to include at least
301 one of the following in your C<use> statement:
302  
303 =over 4
304  
305 =item :all
306  
307 Import all functions.
308  
309 =item :decode
310  
311 Import decode-only functions.
312  
313 =item :encode
314  
315 Import encode-only functions.
316  
317 =item :32
318  
319 Import base32-only functions.
320  
321 =item :58
322  
323 Import base58-only functions.
324  
325 =item :64
326  
327 Import base64-only functions.
328  
329 =back
330  
331 =cut
332  
333 # exporter stuff
334  
335 3 our %EXPORT_TAGS = (
336 all => [qw(to_ncname from_ncname
337 to_ncname_32 from_ncname_32
338 to_ncname_58 from_ncname_58
339 to_ncname_64 from_ncname_64)],
340 decode => [qw(from_ncname from_ncname_32 from_ncname_58 from_ncname_64)],
341 encode => [qw(to_ncname to_ncname_32 to_ncname_58 to_ncname_64)],
342 32 => [qw(to_ncname_32 from_ncname_32)],
343 58 => [qw(to_ncname_58 from_ncname_58)],
344 64 => [qw(to_ncname_64 from_ncname_64)],
345 );
346  
347 # export nothing by default
348 3 our @EXPORT = ();
349 3 our @EXPORT_OK = @{$EXPORT_TAGS{all}};
350  
351 # uuid format string, so meta.
352 3 my $UUF = sprintf('%s-%s-%s-%s-%s', '%02x' x 4, ('%02x' x 2) x 3, '%02x' x 6);
353 # yo dawg i herd u liek format strings so we put a format string in yo
354 # format string
355  
356 # dispatch tables for encoding/decoding
357  
358 my %ENCODE = (
359 2002 ▶ 32 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
360 2002 my @in = unpack 'C*', shift;
361 2002 my $align = shift;
362 2002 ▶ $in[-1] >>= 1 if $align;
Branch: 1 branch
BranchTrueFalseTotal
if $align 2002 0 2002
363 2002 my $out = MIME::Base32::encode_rfc3548(pack 'C*', @in);
364  
365 # we want lower case because IT IS RUDE TO SHOUT
366 2002 lc substr($out, 0, 25);
367 },
368 2000 ▶ 58 => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
369 2000 my @in = unpack 'C*', shift;
370 2000 my $variant = pop(@in) >> 4;
371 # warn unpack 'H*', pack 'C*', @in;
372 2000 my $out = _to_base58(pack 'C*', @in);
373 # warn $out;
374 2000 $out . ('_' x (21 - length $out)) . _encode_version($variant);
375 },
376 2004 ▶ 64 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
377 2004 my @in = unpack 'C*', shift;
378 2004 my $align = shift;
379 2004 ▶ $in[-1] >>= 2 if $align;
Branch: 1 branch
BranchTrueFalseTotal
if $align 2004 0 2004
380  
381 2004 my $out = MIME::Base64::encode(pack 'C*', @in);
382 # note that the rfc4648 sequence ends in +/ or -_
383 2004 $out =~ tr!+/!-_!;
384  
385 2004 substr($out, 0, 21);
386 },
387 3 );
388  
389 my %DECODE = (
390 2000 ▶ 32 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
391 2000 my ($in, $align) = @_;
392  
393 2000 $in = uc substr($in, 0, 25) . '0';
394  
395 2000 my @out = unpack 'C*', MIME::Base32::decode_rfc3548($in);
396 2000 ▶ $out[-1] <<= 1 if $align;
Branch: 1 branch
BranchTrueFalseTotal
if $align 2000 0 2000
397  
398 2000 pack 'C*', @out;
399 },
400 2000 ▶ 58 => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
401 2000 my ($in, $align) = @_;
402 2000 my ($b58, $variant) = ($in =~ /^(.*)(.)$/);
403 2000 $variant = _decode_version($variant) << 4;
404 2000 $b58 =~ tr/_//d;
405 2000 _from_base58($b58) . chr($variant);
406 },
407 2001 ▶ 64 => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
408 2001 my ($in, $align) = @_;
409  
410 2001 $in = substr($in, 0, 21) . 'A==';
411 # note that the rfc4648 sequence ends in +/ or -_
412 2001 $in =~ tr!-_!+/!;
413  
414 #warn unpack 'H*', MIME::Base64::decode($in);
415  
416 2001 my @out = unpack 'C*', MIME::Base64::decode($in);
417  
418 2001 ▶ $out[-1] <<= 2 if $align;
Branch: 1 branch
BranchTrueFalseTotal
if $align 2001 0 2001
419  
420 2001 pack 'C*', @out;
421 },
422 3 );
423  
424 my @TRANSFORM = (
425 # old version, prior to format change
426 [
427 # _bin_uuid_to_pair
428 3005 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
429 3005 my $data = shift;
430 3005 my @list = unpack 'N4', $data;
431  
432 # take the 4 bits the version
433 3005 my $ver = ($list[1] & 0x0000f000) >> 12;
434 # patch the hole with by shifting everything left by 4 bits
435 3005 $list[1] = ($list[1] & 0xffff0000) |
436 (($list[1] & 0x00000fff) << 4) | ($list[2] >> 28);
437 3005 $list[2] = ($list[2] & 0x0fffffff) << 4 | ($list[3] >> 28);
438 3005 $list[3] <<= 4; # note variant bits are not removed
439  
440 3005 return $ver, pack 'N4', @list;
441 },
442 # _pair_to_bin_uuid
443 3000 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
444 3000 my ($ver, $data) = @_;
445  
446 3000 $ver &= 0xf;
447  
448 3000 my @list = unpack 'N4', $data;
449  
450 3000 $list[3] >>= 4;
451 3000 $list[3] |= (($list[2] & 0xf) << 28);
452 3000 $list[2] >>= 4;
453 3000 $list[2] |= (($list[1] & 0xf) << 28);
454 3000 $list[1] = ($list[1] & 0xffff0000) | ($ver << 12) |
455 (($list[1] >> 4) & 0xfff);
456  
457 #warn unpack 'H*', pack 'N4', @list;
458  
459 3000 pack 'N4', @list;
460 },
461 ],
462 # new version
463 [
464 # _bin_uuid_to_pair
465 3001 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
466 3001 my $data = shift;
467 3001 my @list = unpack 'N4', $data;
468  
469 3001 my $ver = ($list[1] & 0x0000f000) >> 12; # version
470 3001 my $var = ($list[2] & 0xf0000000) >> 24; # variant
471 3001 $list[1] = ($list[1] & 0xffff0000) |
472 (($list[1] & 0x00000fff) << 4) |
473 (($list[2] & 0x0fffffff) >> 24);
474 3001 $list[2] = ($list[2] & 0x00ffffff) << 8 | ($list[3] >> 24);
475 3001 $list[3] = ($list[3] << 8) | $var;
476  
477 3001 return $ver, pack 'N4', @list;
478 },
479 # _pair_to_bin_uuid
480 3001 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
481 3001 my ($ver, $data) = @_;
482  
483 3001 $ver &= 0xf;
484  
485 3001 my @list = unpack 'N4', $data;
486  
487 3001 my $var = ($list[3] & 0xf0) << 24;
488  
489 3001 $list[3] >>= 8;
490 3001 $list[3] |= (($list[2] & 0xff) << 24);
491 3001 $list[2] >>= 8;
492 3001 $list[2] |= (($list[1] & 0xf) << 24) | $var;
493 3001 $list[1] = ($list[1] & 0xffff0000) | ($ver << 12) |
494 (($list[1] >> 4) & 0xfff);
495  
496 #warn unpack 'H*', pack 'N4', @list;
497  
498 3001 pack 'N4', @list;
499 },
500 3 ],
501 );
502  
503 8006 ▶sub _encode_version {
Subroutine _encode_version: called CC=3 SCAR=11.0
504 8006 my $ver = $_[0] & 15;
505 8006 ▶ my $off = ($_[1] // 64) == 32 ? 97 : 65;
Branch: 1 branch
BranchTrueFalseTotal
($_[1] // 64) == 32 ? : 2002 6004 8006
Condition100%2/2
$_[1] // 64
l!l
60062000
MC/DC100%1/1
$_[1] // 64
$_[1]
Truth table100%2/2
A
A= $_[1]
Aresult
11
00
506 # A (0) starts at 65. this should never be higher than F (version
507 # 5) for a valid UUID, but even an invalid one will never be
508 # higher than P (15).
509  
510 # XXX boo-hoo, this will break in EBCDIC.
511 8006 chr($ver + $off);
512 }
513  
514 8001 ▶sub _decode_version {
Subroutine _decode_version: called CC=1 SCAR=0.0
515 # modulo makes sure this always returns between 0 and 15
516 8001 return((ord(uc $_[0]) - 65) % 16);
517 }
518  
519 =head1 SUBROUTINES
520  
521 =head2 to_ncname $UUID [, $RADIX ] [, %PARAMS ]
522  
523 Turn C<$UUID> into an NCName. The UUID can be in the canonical
524 (hyphenated) hexadecimal form, non-hyphenated hexadecimal, Base64
525 (regular and base64url), or binary. The function returns a legal
526 NCName equivalent to the UUID, in either Base32, Base58, or Base64
527 (url), given a specified C<$RADIX> of 32, 58, or 64. If the radix is
528 omitted, Base64 is assumed.
529  
530 The following keyword parameters are also accepted, and override the
531 positional parameters where applicable:
532  
533 =over 4
534  
535 =item radix 32|58|64
536  
537 Either 32 or 64 to explicitly specify Base32, Base58, or Base64
538 output. Defaults to 64.
539  
540 =item version 0|1
541  
542 Version 0 will generate the original version of NCName identifiers,
543 prior to the changes noted above. Version 1 is the new version, which
544 is I<not> backwards-compatible. The default, for a transitional
545 period, is to generate version 0, but complain about it. Set the
546 version explicitly (to 1, or to 0 if you need backwards compatibility)
547 to eliminate the warning messages.
548  
549 =item align $FALSY|$TRUTHY
550  
551 Align the last 4 bits to the Base32/Base64 symbol size. You almost
552 certainly want this, so the default is I<true>. (Does not apply to
553 Base58.)
554  
555 =back
556  
557 =cut
558  
559 6006 ▶sub to_ncname {
Subroutine to_ncname: called CC=10 SCAR=26.0
Pod documented
560 6006 state $dict = slurpy Dict[
561 radix => Optional[Radix],
562 version => Optional[Ver],
563 align => Optional[Item],
564 slurpy Any];
565 6006 state $check = multisig(
566 [AnyUUID, Optional[Radix], $dict],
567 [AnyUUID, $dict]);
568  
569 6006 my ($uuid, $radix, $p) = $check->(@_);
570  
571 # optional radix moved to named parameter
572 6006 ▶ if (ref $radix) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $radix) 4 6002 6006
573 4 $p = $radix;
574 4 undef $radix;
575 }
576  
577 6006 ▶ $radix //= $p->{radix} || 64;
Condition75%3/4
$radix //= $p->{"radix"} || 64
l!l
60024
$p->{'radix'} || 64
l!l
40
MC/DC100%1/1
$radix //= $p->{"radix"} || 64
$radix
Truth table100%2/2
A
A= $radix
Aresult
11
00
578 6006 ▶ $p->{align} = !!($p->{align} // 1);
Condition50%1/2
$p->{"align"} // 1
l!l
06006
MC/DC0%0/1
$p->{"align"} // 1
$p->{"align"}
Truth table50%1/2
A
A= $p->{"align"}
Aresult
11
00
579  
580 6006 ▶ unless (defined $p->{version}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $p->{"version"}) 0 6006 6006
581 0 Carp::carp('Set an explicit `version` to eliminate this warning.' .
582 ' See Data::UUID::NCName docs.');
583 0 $p->{version} = 1;
584 }
585  
586 # type checking has ensured this is Stringable so get the string
587 6006 ▶ $uuid = _to_string($uuid)->($uuid) if ref $uuid;
Branch: 1 branch
BranchTrueFalseTotal
if ref $uuid 0 6006 6006
588  
589 # get the uuid into a binary string
590 6006 my $bin;
591 6006 ▶ if (length $uuid == 16) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $uuid == 16) { } 0 6006 6006
592 # this is already a binary string
593 0 $bin = $uuid;
594 }
595 else {
596 # get rid of any whitespace
597 6006 $uuid =~ s/\s+//g;
598  
599 # handle hexadecimal
600 6006 ▶ if ($uuid =~ /^(?i:urn:uuid:)?[0-9A-Fa-f-]{32,}$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($uuid =~ /^(?i:urn:uuid:)?[0-9A-Fa-f-]{32,}$/u) { } 6006 0 6006
elsif ($uuid =~ m[^[0-9A-Za-z=+/_-]$]u) { } 0 0 0
601 6006 $uuid =~ s/^urn:uuid://i;
602 6006 $uuid =~ s/-//g;
603 #warn $uuid;
604 6006 $bin = pack 'H*', $uuid;
605 }
606 # handle base64
607 elsif ($uuid =~ m!^[0-9A-Za-z=+/_-]$!) {
608 # canonicalize first
609 0 $uuid =~ tr!-_!+/!;
610 0 $bin = MIME::Base64::decode($uuid);
611 }
612 else {
613 0 Carp::croak("Couldn't figure out what to do with putative UUID.");
614 }
615 }
616  
617 # extract the version
618 6006 my ($version, $content) = $TRANSFORM[$p->{version}][0]->($bin);
619  
620 # wah-lah.
621 _encode_version($version, $radix) .
622 6006 $ENCODE{$radix}->($content, $p->{align});
623 }
624  
625 =head2 from_ncname $NCNAME [, $FORMAT [, $RADIX] ] [, %PARAMS ]
626  
627 Turn an appropriate C<$NCNAME> back into a UUID, where I<appropriate>,
628 unless overridden by C<$RADIX>, is defined beginning with one initial
629 alphabetic letter (A to Z, case-insensitive) followed by either:
630  
631 =over 4
632  
633 =item B<25> Base32 characters, or
634  
635 =item B<21> Base64URL characters.
636  
637 =back
638  
639 The function will return C<undef> immediately if it cannot match
640 either of these patterns. Input past the 21-character mark (for
641 Base64) or 25-character mark (for Base32) is ignored.
642  
643 This function returns a UUID of type C<$FORMAT>, which if left
644 undefined, must be one of the following:
645  
646 =over 4
647  
648 =item str
649  
650 The canonical UUID format, like so:
651 C<33fcc995-5d10-477e-a9b4-c9cc405bbf04>. This is the default.
652  
653 =item hex
654  
655 The same thing, minus the hyphens.
656  
657 =item b64
658  
659 Base64.
660  
661 =item bin
662  
663 A binary string.
664  
665 =back
666  
667 This function also takes the new keyword-style parameters:
668  
669 =over 4
670  
671 =item format
672  
673 As above.
674  
675 =item radix
676  
677 As above.
678  
679 =item version
680  
681 Sets the identifier version. Defaults to version 0 with a warning. See
682 the note about setting an explicit C<version> parameter in L</to_ncname>.
683  
684 =item align
685  
686 Assume the last few bits are aligned to the symbol, as in L</to_ncname>.
687  
688 =back
689  
690 =cut
691  
692 my %FORMAT = (
693 6001 ▶ str => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
694 6001 sprintf $UUF, unpack 'C*', shift;
695 },
696 0 ▶ hex => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
697 0 unpack 'H*', shift;
698 },
699 0 ▶ b64 => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
700 0 my $x = MIME::Base64::encode(shift);
701 0 $x =~ s/=+$//;
702 0 $x;
703 },
704 0 ▶ bin => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
705 0 shift;
706 },
707 3 );
708  
709 6001 ▶sub from_ncname {
Subroutine from_ncname: called CC=17 SCAR=34.7
Pod documented
710 6001 state $dict = slurpy Dict[
711 format => Optional[Format],
712 radix => Optional[Radix],
713 version => Optional[Ver],
714 align => Optional[Item],
715 slurpy Any];
716 6001 state $check = multisig(
717 [Str, $dict],
718 [Str, Maybe[Format], Optional[Radix], $dict],
719 [Str, Maybe[Format], $dict],
720 );
721  
722 6001 my ($ncname, $format, $radix, $p) = $check->(@_);
723  
724 # handle vagaries of legacy positional parameters
725 6001 ▶ if (ref $format) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $format) { } 6001 0 6001
elsif (ref $radix) { } 0 0 0
726 6001 $p = $format;
727 6001 undef $format;
728 }
729 elsif (ref $radix) {
730 0 $p = $radix;
731 0 undef $radix;
732 }
733  
734 # unconditional override by key-value radix and format parameters
735 6001 ▶ $radix = $p->{radix} if defined $p->{radix};
Branch: 1 branch
BranchTrueFalseTotal
if defined $p->{"radix"} 6000 1 6001
736  
737 # reuse this variable because it doesn't get used for anything else
738 6001 ▶ $format = $FORMAT{$p->{format} || $format || 'str'};
Condition40%2/5
$p->{'format'} || $format || 'str'
l!l
06001
$p->{"format"} or $format
l!l&&r!l&&!r
006001
MC/DC0%0/2
$p->{'format'} || $format || 'str'
$p->{"format"} $format
Truth table33%1/3
A or B
A= $p->{"format"}B= $format
ABresult
1X1
011
000
739  
740 # coerce align parameter to boolish
741 6001 ▶ $p->{align} = !!($p->{align} // 1);
Condition50%1/2
$p->{"align"} // 1
l!l
06001
MC/DC0%0/1
$p->{"align"} // 1
$p->{"align"}
Truth table50%1/2
A
A= $p->{"align"}
Aresult
11
00
742  
743 # enforce explicit presence of version
744 6001 ▶ unless (defined $p->{version}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $p->{"version"}) 0 6001 6001
745 0 Carp::carp('Set an explicit `version` to eliminate this warning.' .
746 ' See Data::UUID::NCName docs.');
747 0 $p->{version} = 1;
748 }
749  
750 # obviously this must be defined
751 6001 ▶ return unless defined $ncname;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ncname 0 6001 6001
752  
753 # no whitespace
754 6001 $ncname =~ s/^\s*(.*?)\s*$/$1/sm;
755  
756 # note that the rfc4648 sequence ends in +/ or -_
757 6001 ▶ my ($version, $content) = ($ncname =~ /^([A-Za-z])([0-9A-Za-z_-]{21,})$/)
Branch: 1 branch
BranchTrueFalseTotal
() = $ncname =~ /^([A-Za-z])([0-9A-Za-z_-]{21,})$/u or return 6001 0 6001
758 or return;
759  
760 6001 ▶ if ($radix) {
Branch: 1 branch
BranchTrueFalseTotal
if ($radix) { } 6000 1 6001
761 6000 ▶ Carp::croak("Radix must be either 32, 58, or 64, not $radix")
Branch: 1 branch
BranchTrueFalseTotal
unless $radix == 32 or $radix == 58 or $radix == 64 0 6000 6000
Condition83%5/6
$radix == 32 or $radix == 58 or $radix == 64
l!l&&r!l&&!r
400020000
$radix == 32 or $radix == 58
l!l&&r!l&&!r
200020002000
MC/DC0%0/3
$radix == 32 or $radix == 58 or $radix == 64
$radix == 32 $radix == 58 $radix == 64
Truth table75%3/4
A or B or C
A= $radix == 32B= $radix == 58C= $radix == 64
ABCresult
1XX1
01X1
0011
0000
762 unless $radix == 32 || $radix == 58 || $radix == 64;
763 }
764 else {
765 # detect what to do based on input
766 1 my $len = length $ncname;
767  
768 1 ▶ if ($len == 22) {
Branch: 3 branches
BranchTrueFalseTotal
if ($len == 22) { } 1 0 1
elsif ($len == 23) { } 0 0 0
elsif ($len == 26) { } 0 0 0
769 1 $radix = 64;
770 }
771 elsif ($len == 23) {
772 0 $radix = 58;
773 }
774 elsif ($len == 26) {
775 0 $radix = 32;
776 }
777 else {
778 # the regex above should ensure this is never reached.
779 0 Carp::croak
780 ("Not sure what to do with an identifier of length $len.");
781 }
782 }
783  
784 # get this stuff back to canonical form
785 6001 $version = _decode_version($version);
786 # warn $version;
787 6001 $content = $DECODE{$radix}->($content, $p->{align});
788 # warn unpack 'H*', $content;
789  
790 # reassemble the pair
791 6001 my $bin = $TRANSFORM[$p->{version}][1]->($version, $content);
792  
793 # *now* format.
794 6001 $format->($bin);
795 }
796  
797 =head2 to_ncname_64 $UUID [, %PARAMS ]
798  
799 Shorthand for Base64 NCNames.
800  
801 =cut
802  
803 3 ▶sub to_ncname_64 {
Subroutine to_ncname_64: called CC=1 SCAR=0.0
Pod documented
804 3 to_ncname(@_, radix => 64);
805 }
806  
807 =head2 from_ncname_64 $NCNAME [, $FORMAT | %PARAMS ]
808  
809 Ditto.
810  
811 =cut
812  
813 0 ▶sub from_ncname_64 {
Subroutine from_ncname_64: not called CC=1 SCAR=6.9
Pod documented
814 0 from_ncname(@_, radix => 64);
815 }
816  
817 =head2 to_ncname_58 $UUID [, %PARAMS ]
818  
819 Shorthand for Base58 NCNames.
820  
821 =cut
822  
823 0 ▶sub to_ncname_58 {
Subroutine to_ncname_58: not called CC=1 SCAR=6.9
Pod documented
824 0 to_ncname(shift, 58, @_);
825 }
826  
827 =head2 from_ncname_58 $NCNAME [, $FORMAT | %PARAMS ]
828  
829 Ditto.
830  
831 =cut
832  
833 0 ▶sub from_ncname_58 {
Subroutine from_ncname_58: not called CC=1 SCAR=6.9
Pod documented
834 0 from_ncname(@_, radix => 58);
835 }
836  
837 =head2 to_ncname_32 $UUID [, %PARAMS ]
838  
839 Shorthand for Base32 NCNames.
840  
841 =cut
842  
843 2 ▶sub to_ncname_32 {
Subroutine to_ncname_32: called CC=1 SCAR=0.0
Pod documented
844 2 to_ncname(shift, 32, @_);
845 }
846  
847 =head2 from_ncname_32 $NCNAME [, $FORMAT | %PARAMS ]
848  
849 Ditto.
850  
851 =cut
852  
853 0 ▶sub from_ncname_32 {
Subroutine from_ncname_32: not called CC=1 SCAR=6.9
Pod documented
854 0 from_ncname(@_, radix => 32);
855 }
856  
857 =head1 AUTHOR
858  
859 Dorian Taylor, C<< <dorian at cpan.org> >>
860  
861 =head1 BUGS
862  
863 Please report bugs/issues/etc L<in
864 GitHub|https://github.com/doriantaylor/p5-data-uuid-ncname/issues>.
865  
866 =over 4
867  
868 =item * MetaCPAN
869  
870 L<https://metacpan.org/release/Data-UUID-NCName>
871  
872 =item * GitHub repository (bugs also go here)
873  
874 L<https://github.com/doriantaylor/p5-data-uuid-ncname>
875  
876 =item * AnnoCPAN: Annotated CPAN documentation
877  
878 L<http://annocpan.org/dist/Data-UUID-NCName>
879  
880 =item * CPAN Ratings
881  
882 L<http://cpanratings.perl.org/d/Data-UUID-NCName>
883  
884 =back
885  
886 =head1 SEE ALSO
887  
888 =over 4
889  
890 =item
891  
892 L<UUID::Tiny>
893  
894 =item
895  
896 L<Data::UUID>
897  
898 =item
899  
900 L<OSSP::uuid>
901  
902 =item
903  
904 L<RFC 4122|http://tools.ietf.org/html/rfc4122>
905  
906 =item
907  
908 L<RFC 4648|http://tools.ietf.org/html/rfc4648>
909  
910 =item
911  
912 L<Namespaces in XML|http://www.w3.org/TR/xml-names/#NT-NCName>
913 (NCName)
914  
915 =item
916  
917 L<W3C XML Schema Definition Language (XSD) 1.1 Part 2:
918 Datatypes|http://www.w3.org/TR/xmlschema11-2/#ID> (ID)
919  
920 =item
921  
922 L<RDF/XML Syntax Specification
923 (Revised)|http://www.w3.org/TR/rdf-syntax-grammar/#rdf-id>
924  
925 =item
926  
927 L<Turtle|http://www.w3.org/TR/turtle/#BNodes>
928  
929 =back
930  
931 This module lives under the C<Data::> namespace for the purpose of
932 namespace hygiene. The main module I<does not> depend on
933 L<Data::UUID>, howevever the script L<uuid-ncname> I<does> depend on
934 L<UUID::Tiny> to generate UUIDs.
935  
936 =head1 LICENSE AND COPYRIGHT
937  
938 Copyright 2012-2018 Dorian Taylor.
939  
940 Licensed under the Apache License, Version 2.0 (the "License"); you
941 may not use this file except in compliance with the License. You may
942 obtain a copy of the License at
943 L<http://www.apache.org/licenses/LICENSE-2.0> .
944  
945 Unless required by applicable law or agreed to in writing, software
946 distributed under the License is distributed on an "AS IS" BASIS,
947 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
948 implied. See the License for the specific language governing
949 permissions and limitations under the License.
950  
951 =cut
952  
953 3 1; # End of Data::UUID::NCName
↑ Summary