ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/CBOR-XS/XS.pm
(Generate patch)

Comparing CBOR-XS/XS.pm (file contents):
Revision 1.1 by root, Fri Oct 25 23:09:45 2013 UTC vs.
Revision 1.18 by root, Sun Nov 17 05:26:14 2013 UTC

12 $perl_value = decode_cbor $binary_cbor_data; 12 $perl_value = decode_cbor $binary_cbor_data;
13 13
14 # OO-interface 14 # OO-interface
15 15
16 $coder = CBOR::XS->new; 16 $coder = CBOR::XS->new;
17 #TODO 17 $binary_cbor_data = $coder->encode ($perl_value);
18 $perl_value = $coder->decode ($binary_cbor_data);
19
20 # prefix decoding
21
22 my $many_cbor_strings = ...;
23 while (length $many_cbor_strings) {
24 my ($data, $length) = $cbor->decode_prefix ($many_cbor_strings);
25 # data was decoded
26 substr $many_cbor_strings, 0, $length, ""; # remove decoded cbor string
27 }
18 28
19=head1 DESCRIPTION 29=head1 DESCRIPTION
20 30
21WARNING! THIS IS A PRE-ALPHA RELEASE! IT WILL CRASH, CORRUPT YOUR DATA AND 31WARNING! This module is very new, and not very well tested (that's up to
22EAT YOUR CHILDREN! 32you to do). Furthermore, details of the implementation might change freely
33before version 1.0. And lastly, the object serialisation protocol depends
34on a pending IANA assignment, and until that assignment is official, this
35implementation is not interoperable with other implementations (even
36future versions of this module) until the assignment is done.
23 37
24This module converts Perl data structures to CBOR and vice versa. Its 38You are still invited to try out CBOR, and this module.
39
40This module converts Perl data structures to the Concise Binary Object
41Representation (CBOR) and vice versa. CBOR is a fast binary serialisation
42format that aims to use a superset of the JSON data model, i.e. when you
43can represent something in JSON, you should be able to represent it in
44CBOR.
45
46In short, CBOR is a faster and very compact binary alternative to JSON,
47with the added ability of supporting serialisation of Perl objects. (JSON
48often compresses better than CBOR though, so if you plan to compress the
49data later you might want to compare both formats first).
50
51To give you a general idea about speed, with texts in the megabyte range,
52C<CBOR::XS> usually encodes roughly twice as fast as L<Storable> or
53L<JSON::XS> and decodes about 15%-30% faster than those. The shorter the
54data, the worse L<Storable> performs in comparison.
55
56As for compactness, C<CBOR::XS> encoded data structures are usually about
5720% smaller than the same data encoded as (compact) JSON or L<Storable>.
58
25primary goal is to be I<correct> and its secondary goal is to be 59The primary goal of this module is to be I<correct> and the secondary goal
26I<fast>. To reach the latter goal it was written in C. 60is to be I<fast>. To reach the latter goal it was written in C.
27 61
28See MAPPING, below, on how CBOR::XS maps perl values to CBOR values and 62See MAPPING, below, on how CBOR::XS maps perl values to CBOR values and
29vice versa. 63vice versa.
30 64
31=cut 65=cut
32 66
33package CBOR::XS; 67package CBOR::XS;
34 68
35use common::sense; 69use common::sense;
36 70
37our $VERSION = 0.01; 71our $VERSION = 0.08;
38our @ISA = qw(Exporter); 72our @ISA = qw(Exporter);
39 73
40our @EXPORT = qw(encode_cbor decode_cbor); 74our @EXPORT = qw(encode_cbor decode_cbor);
41 75
42use Exporter; 76use Exporter;
43use XSLoader; 77use XSLoader;
78
79use Types::Serialiser;
80
81our $MAGIC = "\xd9\xd9\xf7";
44 82
45=head1 FUNCTIONAL INTERFACE 83=head1 FUNCTIONAL INTERFACE
46 84
47The following convenience methods are provided by this module. They are 85The following convenience methods are provided by this module. They are
48exported by default: 86exported by default:
161 199
162=head2 CBOR -> PERL 200=head2 CBOR -> PERL
163 201
164=over 4 202=over 4
165 203
166=item True, False 204=item integers
167 205
168These CBOR values become C<CBOR::XS::true> and C<CBOR::XS::false>, 206CBOR integers become (numeric) perl scalars. On perls without 64 bit
207support, 64 bit integers will be truncated or otherwise corrupted.
208
209=item byte strings
210
211Byte strings will become octet strings in Perl (the byte values 0..255
212will simply become characters of the same value in Perl).
213
214=item UTF-8 strings
215
216UTF-8 strings in CBOR will be decoded, i.e. the UTF-8 octets will be
217decoded into proper Unicode code points. At the moment, the validity of
218the UTF-8 octets will not be validated - corrupt input will result in
219corrupted Perl strings.
220
221=item arrays, maps
222
223CBOR arrays and CBOR maps will be converted into references to a Perl
224array or hash, respectively. The keys of the map will be stringified
225during this process.
226
227=item null
228
229CBOR null becomes C<undef> in Perl.
230
231=item true, false, undefined
232
233These CBOR values become C<Types:Serialiser::true>,
234C<Types:Serialiser::false> and C<Types::Serialiser::error>,
169respectively. They are overloaded to act almost exactly like the numbers 235respectively. They are overloaded to act almost exactly like the numbers
170C<1> and C<0>. You can check whether a scalar is a CBOR boolean by using 236C<1> and C<0> (for true and false) or to throw an exception on access (for
171the C<CBOR::XS::is_bool> function. 237error). See the L<Types::Serialiser> manpage for details.
172 238
173=item null 239=item CBOR tag 256 (perl object)
174 240
175A CBOR Null value becomes C<undef> in Perl. 241The tag value C<256> (TODO: pending iana registration) will be used
242to deserialise a Perl object serialised with C<FREEZE>. See L<OBJECT
243SERIALISATION>, below, for details.
244
245=item CBOR tag 55799 (magic header)
246
247The tag 55799 is ignored (this tag implements the magic header).
248
249=item other CBOR tags
250
251Tagged items consists of a numeric tag and another CBOR value. Tags not
252handled internally are currently converted into a L<CBOR::XS::Tagged>
253object, which is simply a blessed array reference consisting of the
254numeric tag value followed by the (decoded) CBOR value.
255
256In the future, support for user-supplied conversions might get added.
257
258=item anything else
259
260Anything else (e.g. unsupported simple values) will raise a decoding
261error.
176 262
177=back 263=back
178 264
179 265
180=head2 PERL -> CBOR 266=head2 PERL -> CBOR
185 271
186=over 4 272=over 4
187 273
188=item hash references 274=item hash references
189 275
190Perl hash references become CBOR maps. As there is no inherent ordering 276Perl hash references become CBOR maps. As there is no inherent ordering in
191in hash keys (or CBOR maps), they will usually be encoded in a 277hash keys (or CBOR maps), they will usually be encoded in a pseudo-random
192pseudo-random order. 278order.
279
280Currently, tied hashes will use the indefinite-length format, while normal
281hashes will use the fixed-length format.
193 282
194=item array references 283=item array references
195 284
196Perl array references become CBOR arrays. 285Perl array references become fixed-length CBOR arrays.
197 286
198=item other references 287=item other references
199 288
200Other unblessed references are generally not allowed and will cause an 289Other unblessed references are generally not allowed and will cause an
201exception to be thrown, except for references to the integers C<0> and 290exception to be thrown, except for references to the integers C<0> and
202C<1>, which get turned into C<False> and C<True> in CBOR. 291C<1>, which get turned into false and true in CBOR.
203 292
204=item CBOR::XS::true, CBOR::XS::false 293=item CBOR::XS::Tagged objects
205 294
295Objects of this type must be arrays consisting of a single C<[tag, value]>
296pair. The (numerical) tag will be encoded as a CBOR tag, the value will
297be encoded as appropriate for the value. You cna use C<CBOR::XS::tag> to
298create such objects.
299
300=item Types::Serialiser::true, Types::Serialiser::false, Types::Serialiser::error
301
206These special values become CBOR True and CBOR False values, 302These special values become CBOR true, CBOR false and CBOR undefined
207respectively. You can also use C<\1> and C<\0> directly if you want. 303values, respectively. You can also use C<\1>, C<\0> and C<\undef> directly
304if you want.
208 305
209=item blessed objects 306=item other blessed objects
210 307
211Blessed objects are not directly representable in CBOR. TODO 308Other blessed objects are serialised via C<TO_CBOR> or C<FREEZE>. See
212See the 309L<OBJECT SERIALISATION>, below, for details.
213C<allow_blessed> and C<convert_blessed> methods on various options on
214how to deal with this: basically, you can choose between throwing an
215exception, encoding the reference as if it weren't blessed, or provide
216your own serialiser method.
217 310
218=item simple scalars 311=item simple scalars
219 312
220TODO 313TODO
221Simple Perl scalars (any scalar that is not a reference) are the most 314Simple Perl scalars (any scalar that is not a reference) are the most
222difficult objects to encode: CBOR::XS will encode undefined scalars as 315difficult objects to encode: CBOR::XS will encode undefined scalars as
223CBOR C<Null> values, scalars that have last been used in a string context 316CBOR null values, scalars that have last been used in a string context
224before encoding as CBOR strings, and anything else as number value: 317before encoding as CBOR strings, and anything else as number value:
225 318
226 # dump as number 319 # dump as number
227 encode_cbor [2] # yields [2] 320 encode_cbor [2] # yields [2]
228 encode_cbor [-3.0e17] # yields [-3e+17] 321 encode_cbor [-3.0e17] # yields [-3e+17]
250 343
251You can not currently force the type in other, less obscure, ways. Tell me 344You can not currently force the type in other, less obscure, ways. Tell me
252if you need this capability (but don't forget to explain why it's needed 345if you need this capability (but don't forget to explain why it's needed
253:). 346:).
254 347
255Note that numerical precision has the same meaning as under Perl (so 348Perl values that seem to be integers generally use the shortest possible
256binary to decimal conversion follows the same rules as in Perl, which 349representation. Floating-point values will use either the IEEE single
257can differ to other languages). Also, your perl interpreter might expose 350format if possible without loss of precision, otherwise the IEEE double
258extensions to the floating point numbers of your platform, such as 351format will be used. Perls that use formats other than IEEE double to
259infinities or NaN's - these cannot be represented in CBOR, and it is an 352represent numerical values are supported, but might suffer loss of
260error to pass those in. 353precision.
261 354
262=back 355=back
263 356
357=head2 OBJECT SERIALISATION
264 358
359This module knows two way to serialise a Perl object: The CBOR-specific
360way, and the generic way.
361
362Whenever the encoder encounters a Perl object that it cnanot serialise
363directly (most of them), it will first look up the C<TO_CBOR> method on
364it.
365
366If it has a C<TO_CBOR> method, it will call it with the object as only
367argument, and expects exactly one return value, which it will then
368substitute and encode it in the place of the object.
369
370Otherwise, it will look up the C<FREEZE> method. If it exists, it will
371call it with the object as first argument, and the constant string C<CBOR>
372as the second argument, to distinguish it from other serialisers.
373
374The C<FREEZE> method can return any number of values (i.e. zero or
375more). These will be encoded as CBOR perl object, together with the
376classname.
377
378If an object supports neither C<TO_CBOR> nor C<FREEZE>, encoding will fail
379with an error.
380
381Objects encoded via C<TO_CBOR> cannot be automatically decoded, but
382objects encoded via C<FREEZE> can be decoded using the following protocol:
383
384When an encoded CBOR perl object is encountered by the decoder, it will
385look up the C<THAW> method, by using the stored classname, and will fail
386if the method cannot be found.
387
388After the lookup it will call the C<THAW> method with the stored classname
389as first argument, the constant string C<CBOR> as second argument, and all
390values returned by C<FREEZE> as remaining arguments.
391
392=head4 EXAMPLES
393
394Here is an example C<TO_CBOR> method:
395
396 sub My::Object::TO_CBOR {
397 my ($obj) = @_;
398
399 ["this is a serialised My::Object object", $obj->{id}]
400 }
401
402When a C<My::Object> is encoded to CBOR, it will instead encode a simple
403array with two members: a string, and the "object id". Decoding this CBOR
404string will yield a normal perl array reference in place of the object.
405
406A more useful and practical example would be a serialisation method for
407the URI module. CBOR has a custom tag value for URIs, namely 32:
408
409 sub URI::TO_CBOR {
410 my ($self) = @_;
411 my $uri = "$self"; # stringify uri
412 utf8::upgrade $uri; # make sure it will be encoded as UTF-8 string
413 CBOR::XS::tagged 32, "$_[0]"
414 }
415
416This will encode URIs as a UTF-8 string with tag 32, which indicates an
417URI.
418
419Decoding such an URI will not (currently) give you an URI object, but
420instead a CBOR::XS::Tagged object with tag number 32 and the string -
421exactly what was returned by C<TO_CBOR>.
422
423To serialise an object so it can automatically be deserialised, you need
424to use C<FREEZE> and C<THAW>. To take the URI module as example, this
425would be a possible implementation:
426
427 sub URI::FREEZE {
428 my ($self, $serialiser) = @_;
429 "$self" # encode url string
430 }
431
432 sub URI::THAW {
433 my ($class, $serialiser, $uri) = @_;
434
435 $class->new ($uri)
436 }
437
438Unlike C<TO_CBOR>, multiple values can be returned by C<FREEZE>. For
439example, a C<FREEZE> method that returns "type", "id" and "variant" values
440would cause an invocation of C<THAW> with 5 arguments:
441
442 sub My::Object::FREEZE {
443 my ($self, $serialiser) = @_;
444
445 ($self->{type}, $self->{id}, $self->{variant})
446 }
447
448 sub My::Object::THAW {
449 my ($class, $serialiser, $type, $id, $variant) = @_;
450
451 $class-<new (type => $type, id => $id, variant => $variant)
452 }
453
454
455=head1 MAGIC HEADER
456
457There is no way to distinguish CBOR from other formats
458programmatically. To make it easier to distinguish CBOR from other
459formats, the CBOR specification has a special "magic string" that can be
460prepended to any CBOR string without changing its meaning.
461
462This string is available as C<$CBOR::XS::MAGIC>. This module does not
463prepend this string to the CBOR data it generates, but it will ignore it
464if present, so users can prepend this string as a "file type" indicator as
465required.
466
467
468=head1 THE CBOR::XS::Tagged CLASS
469
470CBOR has the concept of tagged values - any CBOR value can be tagged with
471a numeric 64 bit number, which are centrally administered.
472
473C<CBOR::XS> handles a few tags internally when en- or decoding. You can
474also create tags yourself by encoding C<CBOR::XS::Tagged> objects, and the
475decoder will create C<CBOR::XS::Tagged> objects itself when it hits an
476unknown tag.
477
478These objects are simply blessed array references - the first member of
479the array being the numerical tag, the second being the value.
480
481You can interact with C<CBOR::XS::Tagged> objects in the following ways:
482
483=over 4
484
485=item $tagged = CBOR::XS::tag $tag, $value
486
487This function(!) creates a new C<CBOR::XS::Tagged> object using the given
488C<$tag> (0..2**64-1) to tag the given C<$value> (which can be any Perl
489value that can be encoded in CBOR, including serialisable Perl objects and
490C<CBOR::XS::Tagged> objects).
491
492=item $tagged->[0]
493
494=item $tagged->[0] = $new_tag
495
496=item $tag = $tagged->tag
497
498=item $new_tag = $tagged->tag ($new_tag)
499
500Access/mutate the tag.
501
502=item $tagged->[1]
503
504=item $tagged->[1] = $new_value
505
506=item $value = $tagged->value
507
508=item $new_value = $tagged->value ($new_value)
509
510Access/mutate the tagged value.
511
512=back
513
514=cut
515
516sub tag($$) {
517 bless [@_], CBOR::XS::Tagged::;
518}
519
520sub CBOR::XS::Tagged::tag {
521 $_[0][0] = $_[1] if $#_;
522 $_[0][0]
523}
524
525sub CBOR::XS::Tagged::value {
526 $_[0][1] = $_[1] if $#_;
527 $_[0][1]
528}
529
530=head2 EXAMPLES
531
532Here are some examples of C<CBOR::XS::Tagged> uses to tag objects.
533
534You can look up CBOR tag value and emanings in the IANA registry at
535L<http://www.iana.org/assignments/cbor-tags/cbor-tags.xhtml>.
536
537Prepend a magic header (C<$CBOR::XS::MAGIC>):
538
539 my $cbor = encode_cbor CBOR::XS::tag 55799, $value;
540 # same as:
541 my $cbor = $CBOR::XS::MAGIC . encode_cbor $value;
542
543Serialise some URIs and a regex in an array:
544
545 my $cbor = encode_cbor [
546 (CBOR::XS::tag 32, "http://www.nethype.de/"),
547 (CBOR::XS::tag 32, "http://software.schmorp.de/"),
548 (CBOR::XS::tag 35, "^[Pp][Ee][Rr][lL]\$"),
549 ];
550
551Wrap CBOR data in CBOR:
552
553 my $cbor_cbor = encode_cbor
554 CBOR::XS::tag 24,
555 encode_cbor [1, 2, 3];
556
265=head2 CBOR and JSON 557=head1 CBOR and JSON
266 558
267TODO 559CBOR is supposed to implement a superset of the JSON data model, and is,
560with some coercion, able to represent all JSON texts (something that other
561"binary JSON" formats such as BSON generally do not support).
562
563CBOR implements some extra hints and support for JSON interoperability,
564and the spec offers further guidance for conversion between CBOR and
565JSON. None of this is currently implemented in CBOR, and the guidelines
566in the spec do not result in correct round-tripping of data. If JSON
567interoperability is improved in the future, then the goal will be to
568ensure that decoded JSON data will round-trip encoding and decoding to
569CBOR intact.
268 570
269 571
270=head1 SECURITY CONSIDERATIONS 572=head1 SECURITY CONSIDERATIONS
271 573
272When you are using CBOR in a protocol, talking to untrusted potentially 574When you are using CBOR in a protocol, talking to untrusted potentially
340Please refrain from using rt.cpan.org or any other bug reporting 642Please refrain from using rt.cpan.org or any other bug reporting
341service. I put the contact address into my modules for a reason. 643service. I put the contact address into my modules for a reason.
342 644
343=cut 645=cut
344 646
345our $true = do { bless \(my $dummy = 1), "CBOR::XS::Boolean" };
346our $false = do { bless \(my $dummy = 0), "CBOR::XS::Boolean" };
347
348sub true() { $true }
349sub false() { $false }
350
351sub is_bool($) {
352 UNIVERSAL::isa $_[0], "CBOR::XS::Boolean"
353# or UNIVERSAL::isa $_[0], "CBOR::Literal"
354}
355
356XSLoader::load "CBOR::XS", $VERSION; 647XSLoader::load "CBOR::XS", $VERSION;
357
358package CBOR::XS::Boolean;
359
360use overload
361 "0+" => sub { ${$_[0]} },
362 "++" => sub { $_[0] = ${$_[0]} + 1 },
363 "--" => sub { $_[0] = ${$_[0]} - 1 },
364 fallback => 1;
365
3661;
367 648
368=head1 SEE ALSO 649=head1 SEE ALSO
369 650
370The L<JSON> and L<JSON::XS> modules that do similar, but human-readable, 651The L<JSON> and L<JSON::XS> modules that do similar, but human-readable,
371serialisation. 652serialisation.
372 653
654The L<Types::Serialiser> module provides the data model for true, false
655and error values.
656
373=head1 AUTHOR 657=head1 AUTHOR
374 658
375 Marc Lehmann <schmorp@schmorp.de> 659 Marc Lehmann <schmorp@schmorp.de>
376 http://home.schmorp.de/ 660 http://home.schmorp.de/
377 661
378=cut 662=cut
379 663
6641
665

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines