forked from PocketMine/PocketMine-SPL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplFixedByteArray.php
107 lines (94 loc) · 2.28 KB
/
SplFixedByteArray.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/*
* PocketMine Standard PHP Library
* Copyright (C) 2014 PocketMine Team <https://github.com/PocketMine/PocketMine-SPL>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
class SplFixedByteArray extends SplFixedArray{
private $convert;
public function __construct($size, $convert = false){
parent::__construct($size);
$this->convert = (bool) $convert;
}
public function chunk($start, $size, $normalize = true){
$end = $start + $size;
if($normalize and $this->convert){
$d = "";
for($i = $start; $i < $end; ++$i){
$d .= chr($this[$i]);
}
}else{
$d = [];
for($i = $start; $i < $end; ++$i){
$d[] = $this[$i];
}
}
return $d;
}
/**
* @param string $str
* @param bool $convert
*
* @return SplFixedByteArray
*/
public static function fromString($str, $convert = false){
$len = strlen($str);
$ob = new SplFixedByteArray($len, $convert);
if($convert){
for($i = 0; $i < $len; ++$i){
$ob[$i] = ord($str{$i});
}
}else{
for($i = 0; $i < $len; ++$i){
$ob[$i] = $str{$i};
}
}
return $ob;
}
/**
* @param string $str
* @param int $size
* @param int $start
* @param bool $convert
*
* @return SplFixedByteArray
*/
public static function fromStringChunk($str, $size, $start = 0, $convert = false){
$ob = new SplFixedByteArray($size, $convert);
if($convert){
for($i = 0; $i < $size; ++$i){
$ob[$i] = ord($str{$i + $start});
}
}else{
for($i = 0; $i < $size; ++$i){
$ob[$i] = $str{$i + $start};
}
}
return $ob;
}
public function toString(){
$result = "";
if($this->convert){
for($i = 0; $i < $this->getSize(); ++$i){
$result .= chr($this[$i]);
}
}else{
for($i = 0; $i < $this->getSize(); ++$i){
$result .= $this[$i];
}
}
return $result;
}
public function __toString(){
return $this->toString();
}
}