@@ -51,30 +51,31 @@ public static function encode(array $data, ?TypeMarker $type = null): self
5151
5252 $ minValue = count ($ data ) ? min ($ data ) : 0 ;
5353 $ maxValue = count ($ data ) ? max ($ data ) : 0 ;
54- $ packFormat = '' ;
5554
56- if ($ anyFloat ) {
57- if ($ minValue >= 1.4e-45 && $ maxValue <= 3.4028235e+38 ) { // Single precision float (FLOAT_32)
58- if ($ type === null ) $ type = TypeMarker::FLOAT_32 ;
55+ if ($ type === null ) {
56+ $ type = self ::detectTypeMarker ($ anyFloat , $ minValue , $ maxValue );
57+ }
58+
59+ $ packFormat = '' ;
60+ switch ($ type ) {
61+ case TypeMarker::FLOAT_32 :
5962 $ packFormat = 'G ' ;
60- } else { // Double precision float (FLOAT_64)
61- if ( $ type === null ) $ type = TypeMarker::FLOAT_64 ;
63+ break ;
64+ case TypeMarker::FLOAT_64 :
6265 $ packFormat = 'E ' ;
63- }
64- } else {
65- if ($ minValue >= -128 && $ maxValue <= 127 ) { // INT_8
66- if ($ type === null ) $ type = TypeMarker::INT_8 ;
66+ break ;
67+ case TypeMarker::INT_8 :
6768 $ packFormat = 'c ' ;
68- } elseif ( $ minValue >= - 32768 && $ maxValue <= 32767 ) { // INT_16
69- if ( $ type === null ) $ type = TypeMarker::INT_16 ;
69+ break ;
70+ case TypeMarker::INT_16 :
7071 $ packFormat = 's ' ;
71- } elseif ( $ minValue >= - 2147483648 && $ maxValue <= 2147483647 ) { // INT_32
72- if ( $ type === null ) $ type = TypeMarker::INT_32 ;
72+ break ;
73+ case TypeMarker::INT_32 :
7374 $ packFormat = 'l ' ;
74- } else { // INT_64
75- if ( $ type === null ) $ type = TypeMarker::INT_64 ;
75+ break ;
76+ case TypeMarker::INT_64 :
7677 $ packFormat = 'q ' ;
77- }
78+ break ;
7879 }
7980
8081 // Pack the data
@@ -88,6 +89,27 @@ public static function encode(array $data, ?TypeMarker $type = null): self
8889 return new self (new Bytes ([chr ($ type ->value )]), new Bytes ($ packed ));
8990 }
9091
92+ private static function detectTypeMarker (bool $ anyFloat , int |float $ minValue , int |float $ maxValue ): TypeMarker
93+ {
94+ if ($ anyFloat ) {
95+ if ($ minValue >= -3.4028235e+38 && $ maxValue <= 3.4028235e+38 ) { // Single precision float (FLOAT_32)
96+ return TypeMarker::FLOAT_32 ;
97+ } else { // Double precision float (FLOAT_64)
98+ return TypeMarker::FLOAT_64 ;
99+ }
100+ } else {
101+ if ($ minValue >= -128 && $ maxValue <= 127 ) { // INT_8
102+ return TypeMarker::INT_8 ;
103+ } elseif ($ minValue >= -32768 && $ maxValue <= 32767 ) { // INT_16
104+ return TypeMarker::INT_16 ;
105+ } elseif ($ minValue >= -2147483648 && $ maxValue <= 2147483647 ) { // INT_32
106+ return TypeMarker::INT_32 ;
107+ } else { // INT_64
108+ return TypeMarker::INT_64 ;
109+ }
110+ }
111+ }
112+
91113 /**
92114 * Decode vector structure .. returns binary $this->data as array of numbers
93115 * @return int[]|float[]
0 commit comments