|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Alxarafe. Development of PHP applications in a flash! |
|
4
|
|
|
* Copyright (C) 2018-2020 Alxarafe <[email protected]> |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Alxarafe\Core\Utils; |
|
8
|
|
|
|
|
9
|
|
|
use Alxarafe\Core\Singletons\Debug; |
|
10
|
|
|
use Alxarafe\Database\Schema; |
|
11
|
|
|
|
|
12
|
|
|
class MathUtils |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Retorna el número de bytes que son necesarios para almacenar un número que |
|
16
|
|
|
* vaya entre $min y $max, considerando si hay o no signo. |
|
17
|
|
|
* |
|
18
|
|
|
* Téngase en cuenta que min y unsigned son casi excluyentes, pero que unsigned |
|
19
|
|
|
* sí que afecta al tamaño máximo positivo. |
|
20
|
|
|
* |
|
21
|
|
|
* Esta función pretende determinar el tipo de entero necesario. Las |
|
22
|
|
|
* inconsistencias (que no son tales), las tendrá que contemplar quién lo invoque. |
|
23
|
|
|
* |
|
24
|
|
|
* @author Rafael San José Tovar <[email protected]> |
|
25
|
|
|
* |
|
26
|
|
|
* @param int $max |
|
27
|
|
|
* @param int $min |
|
28
|
|
|
* @param bool $unsigned |
|
29
|
|
|
* |
|
30
|
|
|
* @return int |
|
31
|
|
|
*/ |
|
32
|
|
|
public static function howManyBytes(int $max, int $min = 0, bool $unsigned = Schema::DEFAULT_INTEGER_UNSIGNED): int |
|
33
|
|
|
{ |
|
34
|
|
|
if ($min > $max) { |
|
35
|
|
|
Debug::message('Se ha invocado a howManyBytes con el mínimo y máximo cambiados'); |
|
36
|
|
|
$tmp = $min; |
|
37
|
|
|
$min = $max; |
|
38
|
|
|
$max = $tmp; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$bits = log($max + 1, 2); |
|
42
|
|
|
if (!$unsigned) { |
|
43
|
|
|
$bits++; |
|
44
|
|
|
} |
|
45
|
|
|
$bytes = ceil($bits / 8); |
|
46
|
|
|
|
|
47
|
|
|
if ($min >= 0) { |
|
48
|
|
|
return $bytes; |
|
|
|
|
|
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$bits = log(abs($min), 2); |
|
52
|
|
|
$bytesForMin = ceil(($bits + 1) / 8); |
|
53
|
|
|
if ($bytesForMin > $bytes) { |
|
54
|
|
|
return $bytesForMin; |
|
|
|
|
|
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return $bytes; |
|
|
|
|
|
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public static function getMinMax(int $size, $unsigned = true): array |
|
61
|
|
|
{ |
|
62
|
|
|
$bits = 8 * (int) $size; |
|
63
|
|
|
$physicalMaxLength = 2 ** $bits; |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* $minDataLength y $maxDataLength contendrán el mínimo y máximo valor que puede contener el campo. |
|
67
|
|
|
*/ |
|
68
|
|
|
$minDataLength = $unsigned ? 0 : -$physicalMaxLength / 2; |
|
69
|
|
|
$maxDataLength = ($unsigned ? $physicalMaxLength : $physicalMaxLength / 2) - 1; |
|
70
|
|
|
|
|
71
|
|
|
return [ |
|
72
|
|
|
'min' => $minDataLength, |
|
73
|
|
|
'max' => $maxDataLength, |
|
74
|
|
|
]; |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|