Exemple #1
0
Buffer::$protoMethods = array('get' => function ($index) {
    $self = Func::getContext();
    $i = (int) $index;
    if ($i < 0 || $i >= $self->length) {
        throw new Ex(Error::create('offset is out of bounds'));
    }
    return (double) ord($self->raw[$i]);
}, 'set' => function ($index, $byte) {
    $self = Func::getContext();
    $i = (int) $index;
    if ($i < 0 || $i >= $self->length) {
        throw new Ex(Error::create('offset is out of bounds'));
    }
    $old = $self->raw;
    $self->raw = substr($old, 0, $i) . chr($byte) . substr($old, $i + 1);
    return $self->raw;
}, 'write' => function ($data, $enc = null, $start = null, $len = null) {
    $self = Func::getContext();
    //allow second argument (enc) to be omitted
    if (func_num_args() > 1 && !is_string($enc)) {
        $len = $start;
        $start = $enc;
        $enc = null;
    }
    $data = new Buffer($data, $enc);
    $new = $data->raw;
    if ($len !== null) {
        $newLen = (int) $len;
        $new = substr($new, 0, $newLen);
    } else {
        $newLen = $data->length;
    }
    $start = (int) $start;
    $old = $self->raw;
    $oldLen = $self->length;
    if ($start + $newLen > strlen($old)) {
        $newLen = $oldLen - $start;
    }
    $pre = $start === 0 ? '' : substr($old, 0, $start);
    $self->raw = $pre . $new . substr($old, $start + $newLen);
}, 'slice' => function ($start, $end = null) {
    $self = Func::getContext();
    $len = $self->length;
    if ($len === 0) {
        return new Buffer(0);
    }
    $start = (int) $start;
    if ($start < 0) {
        $start = $len + $start;
        if ($start < 0) {
            $start = 0;
        }
    }
    if ($start >= $len) {
        return new Buffer(0);
    }
    $end = $end === null ? $len : (int) $end;
    if ($end < 0) {
        $end = $len + $end;
    }
    if ($end < $start) {
        $end = $start;
    }
    if ($end > $len) {
        $end = $len;
    }
    $new = substr($self->raw, $start, $end - $start);
    return new Buffer($new, 'binary');
}, 'toString' => function ($enc = 'utf8', $start = null, $end = null) {
    $self = Func::getContext();
    $raw = $self->raw;
    if (func_num_args() > 1) {
        $raw = substr($raw, $start, $end - $start + 1);
    }
    if ($enc === 'hex') {
        return bin2hex($raw);
    }
    if ($enc === 'base64') {
        return base64_encode($raw);
    }
    return $raw;
}, 'toJSON' => function () {
    $self = Func::getContext();
    return $self->toJSON();
}, 'inspect' => function () {
    $self = Func::getContext();
    return $self->toJSON(Buffer::$SHOW_MAX);
}, 'clone' => function () {
    $self = Func::getContext();
    return new Buffer($self->raw, 'binary');
});