Decodes a zigzag integer of the given bits.

@param \Protobuf\Stream $stream

@return integer
337919
public function readZigzag(Stream $stream)
    {
        $number = $this->readVarint($stream);
        $zigzag = ($number >> 1) ^ (-($number & 1));

        return $zigzag;
    }
1131909
public function pipe($stream)
    {
        $offset = $stream->tell();
        $result = stream_copy_to_stream($this->resource(), $stream->resource());
        if ($stream->isSeekable()) {
            $stream->seek($offset);
        }
        return $result;
    }
621275
def decode(self, stream, encoding='utf-8'):
        
        data = stream.read().decode(encoding).strip("\n")
        if data != "":
            logger.debug(('{0}: decoded "{1}" with encoding '
                          '{2}'.format(self.target_address, data, encoding)))
        return data
381679
private function parseHashList(Stream $stream)
    {
        $hash = [];

        do {
            $key = $stream->expects(Token::TYPE_IDENTIFIER)->getValue();

            $stream->expects(Token::TYPE_SYMBOL, ':');

            $hash[$key] = $this->parseValue($stream);
        } while ($stream->current()->equals(Token::TYPE_SYMBOL, ',') && $stream->expects(Token::TYPE_SYMBOL, ','));

        return $hash;
    }
651158
public function parseCondition(Stream $stream)
    {
        $expr = $this->parseExpr($stream);

        $stream->expects(Token::TYPE_KEYWORD, 'is');

        if ($stream->current()->equals(Token::TYPE_KEYWORD, 'not')) {
            $stream->expects(Token::TYPE_KEYWORD, 'not');

            $not = true;
        } else {
            $not = false;
        }

        if ($stream->current()->equals(Token::TYPE_KEYWORD, 'like')) {
            $stream->expects(Token::TYPE_KEYWORD, 'like');
        }

        $expr = new EqualsNode($expr, $this->parseExpr($stream));

        if ($not === true) {
            $expr = new UnaryPrefixOperatorNode('!', new GroupNode($expr));
        }

        if ($stream->current()->equals(Token::TYPE_KEYWORD, 'and')) {
            $stream->expects(Token::TYPE_KEYWORD, 'and');

            $expr = new BinaryInfixOperatorNode('&&', $expr, $this->parseCondition($stream));
        }

        if ($stream->current()->equals(Token::TYPE_KEYWORD, 'or')) {
            $stream->expects(Token::TYPE_KEYWORD, 'or');

            $expr = new BinaryInfixOperatorNode('||', $expr, $this->parseCondition($stream));
        }

        return $expr;
    }
133629
public function parse(TokenStream $stream)
    {
        if ($stream->match(Token::OPERATOR, array('!', '-'))) {
            $value = $stream->current()->value;
            $stream->next();
            $ret = new Op\Unary($value, $this->parse($stream));
        } elseif ($stream->match(Token::KEYWORD, array('true', 'false'))) {
            $ret = new Node\Expr\Literal($stream->current()->value === 'true');
            $stream->next();
        } elseif ($stream->match(Token::KEYWORD, 'null')) {
            $ret = new Node\Expr\Literal(null);
            $stream->next();
        } elseif ($stream->match(Token::IDENTIFIER)) {
            $name = $stream->current()->value;
            $stream->next();

            $ret = new Node\Expr\Variable($name);
        } elseif ($stream->match(Token::STRING)) {
            $ret = new Node\Expr\Str($stream->current()->value);
            $stream->next();
        } elseif ($stream->match(Token::NUMBER)) {
            $value = $stream->current()->value;
            if (strpos('.', $value) !== false) {
                $ret = new Node\Expr\Number((float)$value);
            } else {
                $ret = new Node\Expr\Number((int)$value);
            }
            $stream->next();
        } elseif ($stream->match(Token::OPERATOR, '(')) {
            $stream->next();
            $ret = new Node\Expr\Parens($this->parse($stream));
            $stream->expect(Token::OPERATOR, ')');
        } elseif ($stream->match(Token::OPERATOR, '[')) {
            $stream->next();
            $ret = new Node\Expr\ListNode();
            if (!$stream->match(Token::OPERATOR, ']')) {
                $ret->append($this->parse($stream));
                while ($stream->match(',')) {
                    $stream->next();
                    $ret->append($this->parse($stream));
                }
            }
            $stream->expect(Token::OPERATOR, ']');
        } else {
            $this->err($stream);
            return null;
        }

        if ($stream->valid()) {
            while ($stream->valid() && $stream->match(Token::OPERATOR, array('(', '.', '['))) {
                $type = $stream->current();

                $stream->next();
                if ($type->value === '(') {
                    $ret = new Node\Expr\Call($ret);
                    if (!$stream->match(Token::OPERATOR, ')')) {
                        do {
                            $arg = $this->parse($stream);
                            $ret->append($arg);

                            if ($stream->match(',')) {
                                $stream->next();
                            } else {
                                break;
                            }
                        } while (true);
                    }
                    $stream->expect(Token::OPERATOR, ')');
                } else {
                    $ret = new Node\Expr\Subscript($ret);

                    if ($type->value === '.') {
                        $token = $stream->expect(Token::IDENTIFIER);
                        $ret->append(new Node\Expr\Str($token->value));
                    } else {
                        $ret->append($this->parse($stream));
                    }

                    switch ($type->value) {
                        case '[':
                            $stream->expect(Token::OPERATOR, ']');
                            break;
                    }
                }
            }
        }

        if ($stream->valid()) {
            if ($stream->match(Token::OPERATOR, self::$INFIX_BINARY) || $stream->match(Token::KEYWORD, 'in')) {
                $value = $stream->current()->value;
                $stream->next();
                $ret = new Op\Binary($value, $ret, $this->parse($stream));
            } elseif ($stream->match(Token::OPERATOR, '?')) {
                $stream->next();
                if ($stream->match(Token::OPERATOR, ':')) {
                    $then = null;
                } else {
                    $then = $this->parse($stream);
                }

                if ($stream->valid() && $stream->match(Token::OPERATOR, ':')) {
                    $stream->next();
                    $else = $this->parse($stream);
                } else {
                    $else = null;
                }
                $ret = new Op\Ternary('?', $ret, $then, $else);
            }
        }

        // little syntactic sugar for function calls without parentheses:
        $allowInlineCallTokens = array(Token::IDENTIFIER, Token::STRING, Token::NUMBER);
        if ($stream->valid() && ($stream->match($allowInlineCallTokens))) {
            $ret = new Node\Expr\Call($ret);
            $ret->append($this->parse($stream));
        }

        return $ret;
    }
316660
public function parseExpr(Stream $stream)
    {
        if ($stream->current()->is(Token::TYPE_STRING | Token::TYPE_SINGLE_QUOTED)) {
            return new ValueFragmentNode($stream->expects(Token::TYPE_STRING | Token::TYPE_SINGLE_QUOTED)->getValue(), 'varchar');
        }

        if ($stream->current()->is(Token::TYPE_STRING | Token::TYPE_DOUBLE_QUOTED)) {
            return new FragmentNode($stream->expects(Token::TYPE_STRING | Token::TYPE_DOUBLE_QUOTED)->getValue());
        }

        if ($stream->current()->is(Token::TYPE_NUMBER)) {
            $value = $stream->expects(Token::TYPE_NUMBER)->getValue();

            return new ValueFragmentNode($value, strpos($value, '.') === false ? 'int8' : 'decimal');
        }

        if ($stream->current()->is(Token::TYPE_CONSTANT)) {
            $value = strtolower($stream->expects(Token::TYPE_CONSTANT)->getValue());

            return new ValueFragmentNode($value, in_array($value, ['true', 'false']) ? 'bool' : null);
        }

        if ($stream->current()->is(Token::TYPE_IDENTIFIER) && $stream->peek()->equals(Token::TYPE_SYMBOL, '(')) {
            $func = $stream->expects(Token::TYPE_IDENTIFIER)->getValue();
            $args = [];

            $stream->expects(Token::TYPE_SYMBOL, '(');

            if (!$stream->current()->equals(Token::TYPE_SYMBOL, ')')) {
                do {
                    $args[] = $this->parseExpr($stream);
                } while ($stream->current()->equals(Token::TYPE_SYMBOL, ',') && $stream->expects(Token::TYPE_SYMBOL, ','));
            }

            $func = new FuncNode($func, $args);

            $stream->expects(Token::TYPE_SYMBOL, ')');

            return $func;
        }

        if ($stream->current()->is(Token::TYPE_IDENTIFIER)) {
            $path = [$stream->expects(Token::TYPE_IDENTIFIER)->getValue()];

            while ($stream->hasNext() && $stream->current()->equals(Token::TYPE_SYMBOL, '.')) {
                $stream->expects(Token::TYPE_SYMBOL, '.');

                $path[] = $stream->expects(Token::TYPE_IDENTIFIER)->getValue();
            }

            return new ReferenceNode($path);
        }

        if ($stream->current()->equals(Token::TYPE_SYMBOL, '{')) {
            $stream->expects(Token::TYPE_SYMBOL, '{');

            $hash = [];

            if (!$stream->current()->equals(Token::TYPE_SYMBOL, '}')) {
                do {
                    $key = $stream->expects(Token::TYPE_IDENTIFIER)->getValue();

                    $stream->expects(Token::TYPE_SYMBOL, ':');

                    $value = $this->parseExpr($stream);

                    $hash[$key] = $value;
                } while ($stream->current()->equals(Token::TYPE_SYMBOL, ',') && $stream->expects(Token::TYPE_SYMBOL, ','));
            }

            $stream->expects(Token::TYPE_SYMBOL, '}');

            return new RowFragmentNode($hash);
        }

        if ($stream->current()->equals(Token::TYPE_SYMBOL, '[')) {
            $stream->expects(Token::TYPE_SYMBOL, '[');

            $array = [];

            if (!$stream->current()->equals(Token::TYPE_SYMBOL, ']')) {
                do {
                    $array[] = $this->parseExpr($stream);
                } while ($stream->current()->equals(Token::TYPE_SYMBOL, ',') && $stream->expects(Token::TYPE_SYMBOL, ','));
            }

            $stream->expects(Token::TYPE_SYMBOL, ']');

            return new SetFragmentNode($array);
        }

        throw new \Exception(sprintf(
            'Fails to parse stream "%s". Unexpected token %s at line %d.',
            $stream->humanize(),
            Token::humanize($stream->current()->getType()),
            $stream->current()->getLine()
        ));
    }
672816
private function parseFragmentTypeAlias(Stream $stream)
    {
        $alias = $stream->expects(Token::TYPE_SYMBOL, '#')->getValue();

        while ($stream->current()->equals(Token::TYPE_SYMBOL, '[')) {
            $stream->expects(Token::TYPE_SYMBOL, '[');
            $stream->expects(Token::TYPE_SYMBOL, ']');

            $alias = sprintf('%s[]', $alias);
        }

        return $alias;
    }
496821
public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
        while (buffer.remaining() >= 64) {
            int val = stream.read();
            if (val < 0) {
                break; // EOF
            }

            if ((val & COMPRESSED_RUN_MASK) == COMPRESSED_RUN_MASK) {
                int count = val & ~COMPRESSED_RUN_MASK;

                int pixel = stream.read();
                if (pixel < 0) {
                    break; // EOF
                }

                for (int i = 0; i < count; i++) {
                    buffer.put((byte) pixel);
                }
            }
            else {
                buffer.put((byte) val);
            }
        }

        return buffer.position();
    }
882889
public function readInteger()
    {
        try {
            $bin = $this->getStream()->read(4);

            return current(unpack('l', $bin));
        } catch (StreamException $e) {
            $this->handleStreamException($e, BinaryStreamAccessException::INT);
        }
    }
1273344
private function parseList(Stream $stream)
    {
        $list = [];

        do {
            $list[] = $this->parseValue($stream);
        } while ($stream->current()->equals(Token::TYPE_SYMBOL, ',') && $stream->expects(Token::TYPE_SYMBOL, ','));

        return $list;
    }
1014470
private function parseClass(Stream $stream)
    {
        $stream->expects(Token::TYPE_KEYWORD, 'new');

        $class = [$stream->expects(Token::TYPE_IDENTIFIER)->getValue()];

        while ($stream->current()->equals(Token::TYPE_SYMBOL, '\\')) {
            $stream->expects(Token::TYPE_SYMBOL, '\\');

            $class[] = $stream->expects(Token::TYPE_IDENTIFIER)->getValue();
        }

        $class = implode('\\', $class);

        $arguments = [];

        if ($stream->current()->equals(Token::TYPE_SYMBOL, '(')) {
            $stream->expects(Token::TYPE_SYMBOL, '(');

            if (!$stream->current()->equals(Token::TYPE_SYMBOL, ')')) {
                $arguments = $this->parseList($stream);
            }

            $stream->expects(Token::TYPE_SYMBOL, ')');
        }

        return new ClassNode($class, $arguments);
    }
648831
public static function decode($data)
    {
        $params = [];
        while ($data) {
            // TODO take care of single byte length values
            // When the highest bit is 1 then 4 byte are used, else 1 byte
            // For both name and value
            /*if ($data[0] >> 7 === 1) {
                // 4 byte
            } else {
                // 1 byte
            }*/
            $header = \unpack('Nname/Nvalue', substr($data, 0, 8));
            $params[substr($data, 8, $header['name'] - 0x80000000)] = substr($data, 8 + $header['name'] - 0x80000000, $header['value'] - 0x80000000);
            $data = substr($data, 8 + ($header['name'] - 0x80000000) + ($header['value'] - 0x80000000));
        }

        return new self($params);
    }
160546
public function hasStream($stream)
    {
        $isInputStream = $stream == $this->getInputStream();
        $isOutputStream = $stream == $this->getOutputStream();
        $isErrStream = $stream == $this->getErrorStream();

        return $isInputStream || $isOutputStream || $isErrStream;
    }
1355937
public function readBinaryStream($stream)
    {
        if (($str = stream_get_contents($stream)) === false || empty($str)) {
            throw new PListException("Error reading stream!");
        }

        $this->parseBinary($str);
    }
377366
public static function getExtBySignature($stream)
    {
        $prefix = strval(bin2hex(mb_strcut($stream, 0, 10)));

        foreach (self::$signatures as $signature => $extension) {
            if (0 === strpos($prefix, strval($signature))) {
                return $extension;
            }
        }

        return '';
    }
577448
function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200" )
    {
        $this->decodeStreamCommon( $request, $stream, $headers, $cookies, $statuscode );

        $contentType = $this->ContentType;
        $charset = $this->Charset;

        // allow request to force an expected response type
        // this is useful if servers do respond with eg. text/plain content-header for json or xml
        if ( ( $forcedType = $request->responseType() ) != '' )
        {
            list ( $contentType, $charset2 ) = $this->parseContentTypeHeader( $forcedType );
            $this->ContentType = $contentType . '; received="' . $this->ContentType . '"';
            if ( $charset2 != '' )
            {
                $charset = $charset2;
                $this->Charset = $charset . '; received="' . $this->Charset . '"';
            }
        }

        // Allow empty payloads regardless of declared content type, for 204 and 205 responses
        if ( $statuscode == '204' || $statuscode == '205' )
        {
            if ( $stream == '' && ( !isset( $headers['content-length'] ) || $headers['content-length'] == 0 ) )
            {
                $this->Value = null;
                return;
            }
            else
            {
                /// @todo this is not valid according to rfc 2616 - but we should leave that control to client really
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (received http response 204/205 with a body. Not valid http)";
            }
        }

        /// @todo take into account charset when decoding json / xml

        switch( $this->mimeTypeToEncodeType( $contentType ) )
        {
            case 'json':
            case 'application/json':
                $val = json_decode( $stream, true );
                if ( function_exists( 'json_last_error' ) )
                {
                    $err = json_last_error();
                }
                else
                {
                    $err = ( $val === null ) ? 1 : false;
                }
                if ( $err )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' json. Decoding error: ' . $err;
                }
                else
                {
                    $this->Value = $val;
                }
                break;
            case 'xml':
            case 'text/xml':
            case 'application/xml':
                try
                {
                    $doc = new DOMDocument();
                    $prev = libxml_use_internal_errors( true );
                    libxml_clear_errors();
                    $doc->loadXML( $stream );
                    $node = $doc->documentElement;
                    if ( $node == null )
                    {
                        $errors = libxml_get_errors();
                        libxml_use_internal_errors( $prev );
                        $errorText = '';
                        foreach( $errors as $error)
                        {
                            if ( $error->level > LIBXML_ERR_WARNING )
                            {
                                $errorText .= trim ( $error->message ) . ", line: $error->line" . " column: $error->column\n";
                            }
                        }
                        throw new Exception( $errorText );
                    }
                    libxml_use_internal_errors( $prev );
                    $this->Value = new ggSimpleTemplateXML( $node );

                }
                catch ( Exception $e )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' xml. ' . $e->getMessage();
                }
                break;
            case 'text/plain':
            case 'text/html':
                $this->Value = $stream;
                break;
            default:
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (unsupported format $contentType)";
        }
    }