Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/EndpointV2/Bdd/BddNodeDecoder.php

raw symbols SCIP
1 <?php
2
3 namespace Aws\EndpointV2\Bdd;
4
5 use Aws\Exception\UnresolvedEndpointException;
6
7 /**
8 * Decodes the base64 `nodes` string shipped in the endpointBdd trait into a
9 * flat array of signed 32-bit integers. Every node occupies three slots:
10 * `[conditionIndex, highRef, lowRef]`.
11 *
12 * The flat representation is intentional — indexing into an int array is
13 * cheaper per step than materialising a node object for every traversal,
14 * and the evaluator hot loop references thousands of slots for a large BDD.
15 *
16 * @internal
17 */
18 final class BddNodeDecoder
19 {
20 private const BYTES_PER_NODE = 12;
21 private const INT_32_MAX = 2147483647;
22 private const INT_32_OFFSET = 4294967296;
23
24 /**
25 * Decodes `$encoded` and verifies that the byte count matches
26 * `$expectedNodeCount`. Returns a flat int array of length
27 * `3 * $expectedNodeCount`.
28 *
29 * @throws UnresolvedEndpointException when the payload is not valid base64
30 * or its length does not match the declared node count.
31 */
32 public static function decode(string $encoded, int $expectedNodeCount): array
33 {
34 $bytes = base64_decode($encoded, true);
35 if ($bytes === false) {
36 throw new UnresolvedEndpointException(
37 'Endpoint BDD nodes are not valid base64.'
38 );
39 }
40
41 $expectedBytes = $expectedNodeCount * self::BYTES_PER_NODE;
42 if (strlen($bytes) !== $expectedBytes) {
43 throw new UnresolvedEndpointException(sprintf(
44 'Endpoint BDD node payload is %d bytes but %d were expected'
45 . ' for %d nodes.',
46 strlen($bytes),
47 $expectedBytes,
48 $expectedNodeCount
49 ));
50 }
51
52 if ($expectedNodeCount === 0) {
53 return [];
54 }
55
56 // unpack() with 'N' returns unsigned 32-bit big-endian ints. We fold
57 // values above INT_32_MAX back into signed space to match the trait.
58 $unsigned = unpack('N*', $bytes);
59 $flat = [];
60 foreach ($unsigned as $value) {
61 $flat[] = $value > self::INT_32_MAX
62 ? $value - self::INT_32_OFFSET
63 : $value;
64 }
65
66 return $flat;
67 }
68 }