Variable-length integer used in Apple `'dcmp' (0)` and `'dcmp' (1)` compressed resource formats: Perl parsing library

A variable-length integer, in the format used by the 0xfe chunks in the 'dcmp' (0) and 'dcmp' (1) resource compression formats. See the dcmp_0 and dcmp_1 specs for more information about these compression formats.

This variable-length integer format can store an integer x in any of the following ways:

  • In a single byte, if 0 <= x <= 0x7f (7-bit unsigned integer)
  • In 2 bytes, if -0x4000 <= x <= 0x3eff (15-bit signed integer with the highest 0x100 values unavailable)
  • In 5 bytes, if -0x80000000 <= x <= 0x7fffffff (32-bit signed integer)

In practice, values are always stored in the smallest possible format, but technically any of the larger formats could be used as well.

Application

Mac OS

KS implementation details

License: MIT
Minimal Kaitai Struct required: 0.8

This page hosts a formal specification of Variable-length integer used in Apple `'dcmp' (0)` and `'dcmp' (1)` compressed resource formats using Kaitai Struct. This specification can be automatically translated into a variety of programming languages to get a parsing library.

Perl source code to parse Variable-length integer used in Apple `'dcmp' (0)` and `'dcmp' (1)` compressed resource formats

DcmpVariableLengthInteger.pm

# This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild

use strict;
use warnings;
use IO::KaitaiStruct 0.009_000;

########################################################################
package DcmpVariableLengthInteger;

our @ISA = 'IO::KaitaiStruct::Struct';

sub from_file {
    my ($class, $filename) = @_;
    my $fd;

    open($fd, '<', $filename) or return undef;
    binmode($fd);
    return new($class, IO::KaitaiStruct::Stream->new($fd));
}

sub new {
    my ($class, $_io, $_parent, $_root) = @_;
    my $self = IO::KaitaiStruct::Struct->new($_io);

    bless $self, $class;
    $self->{_parent} = $_parent;
    $self->{_root} = $_root || $self;;

    $self->_read();

    return $self;
}

sub _read {
    my ($self) = @_;

    $self->{first} = $self->{_io}->read_u1();
    if ($self->first() >= 128) {
        my $_on = $self->first();
        if ($_on == 255) {
            $self->{more} = $self->{_io}->read_s4be();
        }
        else {
            $self->{more} = $self->{_io}->read_u1();
        }
    }
}

sub value {
    my ($self) = @_;
    return $self->{value} if ($self->{value});
    $self->{value} = ($self->first() == 255 ? $self->more() : ($self->first() >= 128 ? ((($self->first() << 8) | $self->more()) - 49152) : $self->first()));
    return $self->{value};
}

sub first {
    my ($self) = @_;
    return $self->{first};
}

sub more {
    my ($self) = @_;
    return $self->{more};
}

1;