Get write buffer asynchronously.

@param int $length Length of data that is going to be written to the write buffer

@return \Generator
509972
public function getWriteBufferAsync(int $length, string $append = ''): \Generator
    {
        $length >>= 2;
        if ($length < 127) {
            $message = chr($length);
        } else {
            $message = chr(127).substr(pack('V', $length), 0, 3);
        }
        $buffer = yield $this->stream->getWriteBuffer(strlen($message) + $length, $append);
        yield $buffer->bufferWrite($message);

        return $buffer;
    }
513796
public static function generate($length, $seed = self::ALNUM) {
        $return = '';
        $seed = (string) $seed;
        $totalChars = mb_strlen($seed) - 1;

        for ($i = 0; $i < $length; ++$i) {
            $return .= $seed[rand(0, $totalChars)];
        }

        return $return;
    }
1110934
private function socketRead($length)
    {
        $read = '';

        do {
            $read .= \fread($this->socket, $length - \strlen($read));
        } while (\strlen($read) < $length && !\feof($this->socket));

        return $read;
    }
485605
public static function rand($length)
    {
        if (!is_int($length)) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Str::rand() expects first argument to be integer, instead saw %s.',
                    gettype($length)
                )
            );
        }

        if (!function_exists('openssl_random_pseudo_bytes')) {
            return self::quickRand($length);
        }

        if (null === ($bytes = openssl_random_pseudo_bytes($length * 2))) {
            throw new \RuntimeException('Cannot generate random string');
        }

        return substr(str_replace(['/', '=', '+'], '', base64_encode($bytes)), 0, $length);
    }
1136220
public function getReadBufferAsync(&$length): \Generator
    {
        $buffer = yield $this->stream->getReadBuffer($l);
        $headers = '';
        $was_crlf = false;
        while (true) {
            $piece = yield $buffer->bufferRead(2);
            $headers .= $piece;
            if ($piece === "\n\r") { // Assume end of headers with \r\n\r\n
                $headers .= yield $buffer->bufferRead(1);
                break;
            }
            if ($was_crlf && $piece === "\r\n") {
                break;
            }
            $was_crlf = $piece === "\r\n";
        }
        $headers = explode("\r\n", $headers);

        list($protocol, $code, $description) = explode(' ', $headers[0], 3);
        list($protocol, $protocol_version) = explode('/', $protocol);
        if ($protocol !== 'HTTP') {
            throw new \danog\MadelineProto\Exception('Wrong protocol');
        }
        $code = (int) $code;
        unset($headers[0]);
        if (array_pop($headers).array_pop($headers) !== '') {
            throw new \danog\MadelineProto\Exception('Wrong last header');
        }
        foreach ($headers as $key => $current_header) {
            unset($headers[$key]);
            $current_header = explode(':', $current_header, 2);
            $headers[strtolower($current_header[0])] = trim($current_header[1]);
        }

        $close = $protocol === 'HTTP/1.0';
        if (isset($headers['connection'])) {
            $close = strtolower($headers['connection']) === 'close';
        }

        if ($code !== 200) {
            $read = '';
            if (isset($headers['content-length'])) {
                $read = yield $buffer->bufferRead((int) $headers['content-length']);
            }

            if ($close) {
                $this->disconnect();
                yield $this->connect($this->ctx);
            }

            \danog\MadelineProto\Logger::log($read);

            $this->code = $this->pack_signed_int(-$code);
            $length = 4;

            return $this;
        }

        if ($close) {
            $this->stream->disconnect();
            yield $this->stream->connect($this->ctx);
        }
        if (isset($headers['content-length'])) {
            $length = (int) $headers['content-length'];
        }

        return $buffer;
    }
38153
protected function read($length) {
		if ($this->length < $length) {
			throw new \Exception('Reading while at end of stream');
		}
		$output = substr($this->data, 0, $length);
		$this->data = substr($this->data, $length);
		$this->length -= $length;
		return $output;
	}
221296
public function writeStream(Stream $stream, $length)
    {
        $target  = $this->stream;
        $source  = $stream->stream;
        $written = stream_copy_to_stream($source, $target);

        if ($written !== $length) {
            throw new RuntimeException('Failed to write stream with ' . $length . ' bytes');
        }

        $this->size = null;

        return $written;
    }
891991
protected function newGenerator($type, $length = null)
	{
		$generator = GeneratorFactory::create($type)->mutate($this)->length($length ?: $this->length);

		if (isset($this->prefix)) {
			$generator->prefix($this->prefix);
		}

		if (isset($this->suffix)) {
			$generator->suffix($this->suffix);
		}

		return $generator;
	}
604866
public function generateRandomString(int $length = 32): string
    {
        if ($length < 1) {
            throw new \RuntimeException('First parameter ($length) must be greater than 0');
        }

        $bytes = $this->generateRandomKey($length);
        return \substr(StringHelper::base64UrlEncode($bytes), 0, $length);
    }
231244
public function getWriteBuffer(int $length, string $append = ''): Promise
    {
        return $this->stream->getWriteBuffer($length, $append);
    }
215039
public static function getRandomString(int $length): string {
		
		// list of available chars for random string
		$availableChars = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYWZ';
		
		// create a random string
		return substr(str_shuffle($availableChars . $availableChars), 0, $length);
		
	}
1251037
public function get( $prompt = "", $length = 1024 ){
		remark( $prompt );
		ob_flush();
		$result = trim( fgets( $this->tty, $length ) );
		return $result;
	}
1259600
public function bufferReadAsync(int $length): \Generator
    {
        $size = fstat($this->memory_stream)['size'];
        $offset = ftell($this->memory_stream);
        $buffer_length = $size - $offset;
        if ($buffer_length < $length && $buffer_length) {
            fseek($this->memory_stream, $offset + $buffer_length);
        }

        while ($buffer_length < $length) {
            $chunk = yield $this->read();
            if ($chunk === null) {
                $this->disconnect();

                throw new \danog\MadelineProto\NothingInTheSocketException();
            }
            fwrite($this->memory_stream, $chunk);
            $buffer_length += strlen($chunk);
        }
        fseek($this->memory_stream, $offset);

        return fread($this->memory_stream, $length);
    }
640520
public function getReadBufferAsync(&$length): \Generator
    {
        $this->read_buffer = yield $this->stream->getReadBuffer($l);

        return $this;
    }
127891
public static function genRandomBytes($length = 16)
    {
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }

        $sslStr = '';

        /*
         * If a secure randomness generator exists use it.
         */
        if (function_exists('openssl_random_pseudo_bytes')) {
            $sslStr = openssl_random_pseudo_bytes($length, $strong);

            if ($strong) {
                return $sslStr;
            }
        }

        /*
         * Collect any entropy available in the system along with a number
         * of time measurements of operating system randomness.
         */
        $bitsPerRound = 2;
        $maxTimeMicro = 400;
        $shaHashLength = 20;
        $randomStr = '';
        $total = $length;

        // Check if we can use /dev/urandom.
        $urandom = false;
        $handle = null;

        if (@is_readable('/dev/urandom')) {
            $handle = @fopen('/dev/urandom', 'rb');

            if ($handle) {
                $urandom = true;
            }
        }

        while ($length > strlen($randomStr)) {
            $bytes = ($total > $shaHashLength) ? $shaHashLength : $total;
            $total -= $bytes;
            /*
             * Collect any entropy available from the PHP system and filesystem.
             * If we have ssl data that isn't strong, we use it once.
             */
            $entropy = mt_rand() . uniqid(mt_rand(), true) . $sslStr;
            $entropy .= implode('', @fstat(fopen(__FILE__, 'r')));
            $entropy .= memory_get_usage();
            $sslStr = '';

            if ($urandom) {
                stream_set_read_buffer($handle, 0);
                $entropy .= @fread($handle, $bytes);
            } else {
                /*
                 * There is no external source of entropy so we repeat calls
                 * to mt_rand until we are assured there's real randomness in
                 * the result.
                 *
                 * Measure the time that the operations will take on average.
                 */
                $samples = 3;
                $duration = 0;

                for ($pass = 0; $pass < $samples; ++$pass) {
                    $microStart = microtime(true) * 1000000;
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < 50; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $microEnd = microtime(true) * 1000000;
                    $entropy .= $microStart . $microEnd;

                    if ($microStart >= $microEnd) {
                        $microEnd += 1000000;
                    }

                    $duration += $microEnd - $microStart;
                }

                $duration = $duration / $samples;

                /*
                 * Based on the average time, determine the total rounds so that
                 * the total running time is bounded to a reasonable number.
                 */
                $rounds = (int) (($maxTimeMicro / $duration) * 50);

                /*
                 * Take additional measurements. On average we can expect
                 * at least $bitsPerRound bits of entropy from each measurement.
                 */
                $iter = $bytes * (int) ceil(8 / $bitsPerRound);

                for ($pass = 0; $pass < $iter; ++$pass) {
                    $microStart = microtime(true);
                    $hash = sha1(mt_rand(), true);

                    for ($count = 0; $count < $rounds; ++$count) {
                        $hash = sha1($hash, true);
                    }

                    $entropy .= $microStart . microtime(true);
                }
            }

            $randomStr .= sha1($entropy, true);
        }

        if ($urandom) {
            @fclose($handle);
        }

        return substr($randomStr, 0, $length);
    }
162229
private function fillBuffer($length)
    {
        // 5040 = 63 * 80, seems to be good balance for buffering in benchmarks
        // testing with a simple 'if ($length < x)' and calculating a better
        // size reduces speeds by up to 4x
        while ($this->buffer->getSize() < $length) {
            $read = $this->readToEndOfLine(5040);
            if ($read === false || $read === '') {
                break;
            }
            $this->buffer->write($this->filterAndDecode($read));
        }
    }
72734
public function read($length)
    {
        // let Guzzle decide what to do.
        if ($length <= 0 || $this->eof()) {
            return $this->stream->read($length);
        }
        $count = 0;
        $bytes = '';
        while ($count < $length) {
            $nRead = $this->readRawDecodeAndAppend($length - $count, $bytes);
            if ($nRead === -1) {
                break;
            }
            $this->position += $nRead;
            $count += $nRead;
        }
        return $bytes;
    }