PocketMine-MP 5.23.3 git-976fc63567edab7a6fb6aeae739f43cf9fe57de4
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 ceil;
27use function count;
28use function log;
29use function spl_object_id;
30use function usort;
31
39 public readonly int $bits;
40
45 private readonly array $intToEnum;
50 private readonly array $enumToInt;
51
56 public function __construct(
57 array $members
58 ){
59 usort($members, fn(\UnitEnum $a, \UnitEnum $b) => $a->name <=> $b->name); //sort by name to ensure consistent ordering (and thus consistent bit assignments)
60
61 $this->bits = (int) ceil(log(count($members), 2));
62 $this->intToEnum = $members; //usort strips keys so this is already a list
63
64 $reversed = [];
65 foreach($this->intToEnum as $int => $enum){
66 $reversed[spl_object_id($enum)] = $int;
67 }
68
69 $this->enumToInt = $reversed;
70 }
71
75 public function intToEnum(int $value) : ?object{
76 return $this->intToEnum[$value] ?? null;
77 }
78
82 public function enumToInt(object $enum) : int{
83 return $this->enumToInt[spl_object_id($enum)];
84 }
85
90 private static array $cache = [];
91
98 public static function from(\UnitEnum $case) : self{
99 $class = $case::class;
101 $metadata = self::$cache[$class] ?? null;
102 if($metadata === null){
107 $cases = $case::cases();
108 self::$cache[$class] = $metadata = new self($cases);
109 }
110
111 return $metadata;
112 }
113}