PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
RuntimeEnumMetadata.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\data\runtime;
25
26use function array_values;
27use function ceil;
28use function count;
29use function log;
30use function spl_object_id;
31use function usort;
32
40 public readonly int $bits;
41
46 private readonly array $intToEnum;
51 private readonly array $enumToInt;
52
57 public function __construct(
58 array $members
59 ){
60 usort($members, fn(\UnitEnum $a, \UnitEnum $b) => $a->name <=> $b->name); //sort by name to ensure consistent ordering (and thus consistent bit assignments)
61
62 $this->bits = (int) ceil(log(count($members), 2));
63 $this->intToEnum = array_values($members);
64
65 $reversed = [];
66 foreach($this->intToEnum as $int => $enum){
67 $reversed[spl_object_id($enum)] = $int;
68 }
69
70 $this->enumToInt = $reversed;
71 }
72
76 public function intToEnum(int $value) : ?object{
77 return $this->intToEnum[$value] ?? null;
78 }
79
83 public function enumToInt(object $enum) : int{
84 return $this->enumToInt[spl_object_id($enum)];
85 }
86
91 private static array $cache = [];
92
99 public static function from(\UnitEnum $case) : self{
100 $class = $case::class;
102 $metadata = self::$cache[$class] ?? null;
103 if($metadata === null){
108 $cases = $case::cases();
109 self::$cache[$class] = $metadata = new self($cases);
110 }
111
112 return $metadata;
113 }
114}