53 public static function pack( $value ) {
55 if ( self::$bigendian ===
null ) {
56 self::$bigendian =
pack(
'S', 1 ) ===
pack(
'n', 1 );
59 switch ( gettype( $value ) ) {
64 return $value ?
"\xC3" :
"\xC2";
68 return self::$bigendian
69 ?
"\xCB" .
pack(
'd', $value )
70 :
"\xCB" . strrev(
pack(
'd', $value ) );
73 $length = strlen( $value );
75 return pack(
'Ca*', 0xA0 | $length, $value );
76 } elseif ( $length <= 0xFFFF ) {
77 return pack(
'Cna*', 0xDA, $length, $value );
78 } elseif ( $length <= 0xFFFFFFFF ) {
79 return pack(
'CNa*', 0xDB, $length, $value );
81 throw new InvalidArgumentException( __METHOD__
82 .
": string too long (length: $length; max: 4294967295)" );
86 if ( $value <= 0x7F ) {
90 if ( $value <= 0xFF ) {
92 return pack(
'CC', 0xCC, $value );
94 if ( $value <= 0xFFFF ) {
96 return pack(
'Cn', 0xCD, $value );
98 if ( $value <= 0xFFFFFFFF ) {
100 return pack(
'CN', 0xCE, $value );
102 if ( $value <= 0xFFFFFFFFFFFFFFFF ) {
104 $hi = ( $value & 0xFFFFFFFF00000000 ) >> 32;
105 $lo = $value & 0xFFFFFFFF;
106 return self::$bigendian
107 ?
pack(
'CNN', 0xCF, $lo, $hi )
108 :
pack(
'CNN', 0xCF, $hi, $lo );
111 if ( $value >= -32 ) {
113 return pack(
'c', $value );
115 if ( $value >= -0x80 ) {
117 return pack(
'Cc', 0xD0, $value );
119 if ( $value >= -0x8000 ) {
121 $p =
pack(
's', $value );
122 return self::$bigendian
123 ?
pack(
'Ca2', 0xD1, $p )
124 :
pack(
'Ca2', 0xD1, strrev( $p ) );
126 if ( $value >= -0x80000000 ) {
128 $p =
pack(
'l', $value );
129 return self::$bigendian
130 ?
pack(
'Ca4', 0xD2, $p )
131 :
pack(
'Ca4', 0xD2, strrev( $p ) );
133 if ( $value >= -0x8000000000000000 ) {
136 $p1 =
pack(
'l', $value & 0xFFFFFFFF );
138 $p2 =
pack(
'l', ( $value >> 32 ) & 0xFFFFFFFF );
139 return self::$bigendian
140 ?
pack(
'Ca4a4', 0xD3, $p1, $p2 )
141 :
pack(
'Ca4a4', 0xD3, strrev( $p2 ), strrev( $p1 ) );
144 throw new InvalidArgumentException( __METHOD__ .
": invalid integer '$value'" );
148 $length = count( $value );
149 if ( $length > 0xFFFFFFFF ) {
150 throw new InvalidArgumentException( __METHOD__
151 .
": array too long (length: $length, max: 4294967295)" );
155 foreach ( $value as $k => $v ) {
156 if ( $index !== $k || $index === $length ) {
162 $associative = $index !== $length;
164 if ( $associative ) {
165 if ( $length < 16 ) {
166 $buffer .=
pack(
'C', 0x80 | $length );
167 } elseif ( $length <= 0xFFFF ) {
168 $buffer .=
pack(
'Cn', 0xDE, $length );
170 $buffer .=
pack(
'CN', 0xDF, $length );
172 foreach ( $value as $k => $v ) {
177 if ( $length < 16 ) {
178 $buffer .=
pack(
'C', 0x90 | $length );
179 } elseif ( $length <= 0xFFFF ) {
180 $buffer .=
pack(
'Cn', 0xDC, $length );
182 $buffer .=
pack(
'CN', 0xDD, $length );
184 foreach ( $value as $v ) {
191 throw new InvalidArgumentException( __METHOD__ .
': unsupported type ' . gettype( $value ) );