VarInt   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Test Coverage

Coverage 75%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 6
dl 0
loc 66
ccs 21
cts 28
cp 0.75
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A solveWriteSize() 0 12 4
A solveReadSize() 0 12 4
A write() 0 9 2
A read() 0 10 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BitWasp\Buffertools\Types;
6
7
use BitWasp\Buffertools\ByteOrder;
8
use BitWasp\Buffertools\Parser;
9
10
class VarInt extends AbstractType
11
{
12
    /**
13
     * @param \GMP $integer
14
     * @return array
15
     */
16 4
    public function solveWriteSize(\GMP $integer)
17
    {
18 4
        if (gmp_cmp($integer, gmp_pow(gmp_init(2), 16)) < 0) {
19 2
            return [new Uint16(ByteOrder::LE), 0xfd];
20 2
        } else if (gmp_cmp($integer, gmp_pow(gmp_init(2), 32)) < 0) {
21
            return [new Uint32(ByteOrder::LE), 0xfe];
22 2
        } else if (gmp_cmp($integer, gmp_pow(gmp_init(2), 64)) < 0) {
23
            return [new Uint64(ByteOrder::LE), 0xff];
24
        } else {
25 2
            throw new \InvalidArgumentException('Integer too large, exceeds 64 bit');
26
        }
27
    }
28
29
    /**
30
     * @param \GMP $givenPrefix
31
     * @return UintInterface[]
32
     * @throws \InvalidArgumentException
33
     */
34 2
    public function solveReadSize(\GMP $givenPrefix)
35
    {
36 2
        if (gmp_cmp($givenPrefix, 0xfd) === 0) {
37 2
            return [new Uint16(ByteOrder::LE)];
38
        } else if (gmp_cmp($givenPrefix, 0xfe) === 0) {
39
            return [new Uint32(ByteOrder::LE)];
40
        } else if (gmp_cmp($givenPrefix, 0xff) === 0) {
41
            return [new Uint64(ByteOrder::LE)];
42
        }
43
44
        throw new \InvalidArgumentException('Unknown varint prefix');
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     * @see \BitWasp\Buffertools\Types\TypeInterface::write()
50
     */
51 10
    public function write($integer): string
52
    {
53 10
        $gmpInt = gmp_init($integer, 10);
54 10
        if (gmp_cmp($gmpInt, gmp_init(0xfd, 10)) < 0) {
55 8
            return pack("C", $integer);
56
        }
57 2
        list ($int, $prefix) = $this->solveWriteSize($gmpInt);
58 2
        return pack("C", $prefix) . $int->write($integer);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     * @see \BitWasp\Buffertools\Types\TypeInterface::read()
64
     */
65 16
    public function read(Parser $parser)
66
    {
67 16
        $byte = unpack("C", $parser->readBytes(1)->getBinary())[1];
68 16
        if ($byte < 0xfd) {
69 14
            return $byte;
70
        }
71
72 2
        list ($uint) = $this->solveReadSize(gmp_init($byte, 10));
73 2
        return $uint->read($parser);
74
    }
75
}
76