Full Code of sevagh/pq for AI

master 94f09f1f693d cached
49 files
67.8 KB
18.4k tokens
130 symbols
1 requests
Download .txt
Repository: sevagh/pq
Branch: master
Commit: 94f09f1f693d
Files: 49
Total size: 67.8 KB

Directory structure:
gitextract_tt0fh83e/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── erased-serde-json/
│   ├── .gitignore
│   ├── Cargo.toml
│   ├── LICENSE-APACHE
│   ├── LICENSE-MIT
│   ├── README.md
│   └── src/
│       ├── lib.rs
│       └── ser.rs
├── src/
│   ├── commands.rs
│   ├── decode.rs
│   ├── discovery.rs
│   ├── formatter.rs
│   └── main.rs
├── stream-delimit/
│   ├── Cargo.toml
│   ├── LICENSE
│   ├── README.md
│   └── src/
│       ├── byte_consumer.rs
│       ├── converter.rs
│       ├── error.rs
│       ├── kafka_consumer.rs
│       ├── lib.rs
│       ├── stream.rs
│       └── varint.rs
├── tests/
│   ├── README.md
│   ├── fdsets/
│   │   ├── cat.fdset
│   │   ├── dog.fdset
│   │   └── person.fdset
│   ├── fdsets-invalid/
│   │   └── .gitignore
│   ├── protos/
│   │   └── dog.proto
│   ├── samples/
│   │   ├── bad
│   │   ├── cat
│   │   ├── dog
│   │   ├── dog_i32be_stream
│   │   ├── dog_stream
│   │   ├── person
│   │   └── person_stream
│   └── test_pqrs_bin.rs
└── utils/
    ├── .gitignore
    ├── GNUmakefile
    ├── README.txt
    ├── cat.proto
    ├── dog.proto
    ├── person.proto
    ├── proto_encoder.py
    └── requirements.txt

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
target
rust
*.tar.gz
*~
*.bk
pq


================================================
FILE: Cargo.toml
================================================
[package]
name = "pq"
version = "1.4.4"
authors = ["Sevag Hanssian <sevag.hanssian@gmail.com>"]
description = "jq for protobuf"
repository = "https://github.com/sevagh/pq"
documentation = "https://github.com/sevagh/pq"
readme = "README.md"
license = "MIT"
keywords = ["protobuf", "serde"]
exclude = ["pq-bin.tar.gz", "pq", "target/**"]
edition = "2021"

[dependencies]
openssl = { version = "0.10", features = ["vendored"] }
serde = "1.0"
erased_serde_json = { path = "erased-serde-json", version = "0.1.3" }
serde_json = "1.0"
serde-protobuf = "0.8"
protobuf = "2.3"
stream_delimit = { path = "stream-delimit", version = "0.5.7" }
clap = "2"
libc = "0.2"
dirs = "2.0"
serde-transcode = ">= 1.1, <2"
default-env = "0.1.1"

[dev-dependencies]
assert_cli = "0.6"

[features]
default = ["stream_delimit/with_kafka"]

[workspace]
members = ["stream-delimit", "erased-serde-json"]
default-members = [".", "stream-delimit", "erased-serde-json"]

[profile.release]
debug = true
lto = true
panic = "abort"


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2017 Sevag Hanssian

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Makefile
================================================
WORKSPACES="./" "./stream-delimit/"
DOCKER_BIN ?= docker
DOCKER_IMAGE=docker.io/clux/muslrust
DOCKER_ARGS=run -v $(PWD):/volume:Z -w /volume -t $(DOCKER_IMAGE)
CARGO_TOKEN:=$(shell grep 'token' ~/.cargo/credentials.toml | cut -d'"' -f2)

all: debug

docker:
	$(DOCKER_BIN) pull $(DOCKER_IMAGE)

debug: docker
	$(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo build --verbose"

release: docker
	$(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo build --verbose --release"

test: docker
	$(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo test --verbose"

publish: docker
	$(DOCKER_BIN) $(DOCKER_ARGS) sh -c "cargo login $(CARGO_TOKEN) && cd stream-delimit && cargo publish ; cd ../ && cd erased-serde-json && cargo publish ; cd ../ && cargo publish"

fmt:
	-cargo fmt --all
	-black utils/*.py

clippy:
	-cargo clippy --all

package: release
	tar -C target/x86_64-unknown-linux-musl/release -czvf pq-bin.tar.gz pq

.PHONY: all debug release package


================================================
FILE: README.md
================================================
# pq [![license](https://img.shields.io/github/license/sevagh/pq.svg)](https://github.com/sevagh/pq/blob/master/LICENSE) [![Crates.io](https://img.shields.io/crates/v/pq.svg)](https://crates.io/crates/pq)

### protobuf to json deserializer, written in Rust

`pq` is a tool which deserializes protobuf messages given a set of pre-compiled `.fdset` files. It can understand varint/leb128-delimited/i32be streams, and it can connect to Kafka.

`pq` will pretty-print when outputting to a tty, but you should pipe it to `jq` for more fully-featured json handling.

### Download

pq is on [crates.io](https://crates.io/crates/pq): `cargo install pq`. You can also download a static binary from the [releases page](https://github.com/sevagh/pq/releases).

### Usage

**new** You can now pass in a proto file and have pq compile it on the fly using `protoc`:

```
$ pq --protofile ./tests/protos/dog.proto  --msgtype com.example.dog.Dog <./tests/samples/dog
{
  "breed": "gsd",
  "age": 3,
  "temperament": "excited"
}
```

Use PROTOC and PROTOC_INCLUDE to control the executed protoc binary and configure the `-I=/proto/path` argument (design copied from [prost](https://github.com/danburkert/prost/blob/master/prost-build/src/lib.rs)).

To set up, put your `*.fdset` files in `~/.pq`, `/etc/pq`, or a different directory specified with the `FDSET_PATH` env var:

```
$ protoc -o dog.fdset dog.proto
$ protoc -o person.fdset person.proto
$ cp *.fdset ~/.pq/
```

You can specify additional fdset directories or files via options:

```
$ pq --msgtype com.example.dog.Dog --fdsetdir ./tests/fdsets <./tests/samples/dog
$ pq --msgtype com.example.dog.Dog --fdsetfile ./tests/fdsets/dog.fdset <./tests/samples/dog
```

Pipe a single compiled protobuf message:

```
$ pq --msgtype com.example.dog.Dog <./tests/samples/dog
{
  "age": 4,
  "breed": "poodle",
  "temperament": "excited"
}
```

Pipe a `varint` or `leb128` delimited stream:

```
$ pq --msgtype com.example.dog.Dog --stream varint <./tests/samples/dog_stream
{
  "age": 10,
  "breed": "gsd",
  "temperament": "aggressive"
}
```

Consume from a Kafka stream:

```
$ pq kafka my_topic --brokers 192.168.0.1:9092 --beginning --count 1 --msgtype com.example.dog.Dog
{
  "age": 10,
  "breed": "gsd",
  "temperament": "aggressive"
}
```

Convert a Kafka stream to varint-delimited:

```
$ pq kafka my_topic --brokers=192.168.0.1:9092 --count 1 --convert varint |\
> pq --msgtype com.example.dog.Dog --stream varint
{
  "age": 10,
  "breed": "gsd",
  "temperament": "aggressive"
}
```

Pipe `kafkacat` output to it:
```
$ kafkacat -b 192.168.0.1:9092 -C -u -q -f "%R%s" -t my_topic |\
> pq --msgtype=com.example.dog.Dog --stream i32be
{
  "age": 10,
  "breed": "gsd",
  "temperament": "aggressive"
}
```

### Compile without kafka

To compile `pq` without kafka support, run:

```
$ cargo build --no-default-features
```

### Compile for Windows

1. Install [Visual Studio Installer](https://visualstudio.microsoft.com/downloads/) Community edition
2. Run the installer and install `Visual Studio Build Tools 2019`. You need the `C++ Build Tools` workload. Note that you can't just install the minimal package, you also need `MSVC C++ x64/86 Build Tools` and `Windows 10 SDK`.
3. Open `x64 Native Tools Command Prompt` from the start menu.
4. Download and run [`rustup-init.exe`](https://win.rustup.rs/x86_64)
5. Close and reopen your terminal (so `cargo` will be in your path)
6. Run `cargo install --no-default-features pq`

Note that this will disable the Kafka feature, which is not currently supported on Windows.


================================================
FILE: erased-serde-json/.gitignore
================================================
target/
**/*.rs.bk
*.sw[po]
Cargo.lock


================================================
FILE: erased-serde-json/Cargo.toml
================================================
[package]
name = "erased_serde_json"
version = "0.1.3"
authors = ["Sevag Hanssian <sevag.hanssian@gmail.com>"]
license = "MIT/Apache-2.0"
description = "Type-erased Formatter trait for serde_json::ser::Formatter"
repository = "https://github.com/sevagh/erased-serde-json"
documentation = "https://github.com/sevagh/erased-serde-json"
keywords = ["json", "serde", "serialization"]
categories = ["encoding"]
readme = "README.md"
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"]
edition = "2018"

[dependencies]
serde = "1.0"
serde_json = "1.0.2"


================================================
FILE: erased-serde-json/LICENSE-APACHE
================================================
                              Apache License
                        Version 2.0, January 2004
                     http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

1. Definitions.

   "License" shall mean the terms and conditions for use, reproduction,
   and distribution as defined by Sections 1 through 9 of this document.

   "Licensor" shall mean the copyright owner or entity authorized by
   the copyright owner that is granting the License.

   "Legal Entity" shall mean the union of the acting entity and all
   other entities that control, are controlled by, or are under common
   control with that entity. For the purposes of this definition,
   "control" means (i) the power, direct or indirect, to cause the
   direction or management of such entity, whether by contract or
   otherwise, or (ii) ownership of fifty percent (50%) or more of the
   outstanding shares, or (iii) beneficial ownership of such entity.

   "You" (or "Your") shall mean an individual or Legal Entity
   exercising permissions granted by this License.

   "Source" form shall mean the preferred form for making modifications,
   including but not limited to software source code, documentation
   source, and configuration files.

   "Object" form shall mean any form resulting from mechanical
   transformation or translation of a Source form, including but
   not limited to compiled object code, generated documentation,
   and conversions to other media types.

   "Work" shall mean the work of authorship, whether in Source or
   Object form, made available under the License, as indicated by a
   copyright notice that is included in or attached to the work
   (an example is provided in the Appendix below).

   "Derivative Works" shall mean any work, whether in Source or Object
   form, that is based on (or derived from) the Work and for which the
   editorial revisions, annotations, elaborations, or other modifications
   represent, as a whole, an original work of authorship. For the purposes
   of this License, Derivative Works shall not include works that remain
   separable from, or merely link (or bind by name) to the interfaces of,
   the Work and Derivative Works thereof.

   "Contribution" shall mean any work of authorship, including
   the original version of the Work and any modifications or additions
   to that Work or Derivative Works thereof, that is intentionally
   submitted to Licensor for inclusion in the Work by the copyright owner
   or by an individual or Legal Entity authorized to submit on behalf of
   the copyright owner. For the purposes of this definition, "submitted"
   means any form of electronic, verbal, or written communication sent
   to the Licensor or its representatives, including but not limited to
   communication on electronic mailing lists, source code control systems,
   and issue tracking systems that are managed by, or on behalf of, the
   Licensor for the purpose of discussing and improving the Work, but
   excluding communication that is conspicuously marked or otherwise
   designated in writing by the copyright owner as "Not a Contribution."

   "Contributor" shall mean Licensor and any individual or Legal Entity
   on behalf of whom a Contribution has been received by Licensor and
   subsequently incorporated within the Work.

2. Grant of Copyright License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   copyright license to reproduce, prepare Derivative Works of,
   publicly display, publicly perform, sublicense, and distribute the
   Work and such Derivative Works in Source or Object form.

3. Grant of Patent License. Subject to the terms and conditions of
   this License, each Contributor hereby grants to You a perpetual,
   worldwide, non-exclusive, no-charge, royalty-free, irrevocable
   (except as stated in this section) patent license to make, have made,
   use, offer to sell, sell, import, and otherwise transfer the Work,
   where such license applies only to those patent claims licensable
   by such Contributor that are necessarily infringed by their
   Contribution(s) alone or by combination of their Contribution(s)
   with the Work to which such Contribution(s) was submitted. If You
   institute patent litigation against any entity (including a
   cross-claim or counterclaim in a lawsuit) alleging that the Work
   or a Contribution incorporated within the Work constitutes direct
   or contributory patent infringement, then any patent licenses
   granted to You under this License for that Work shall terminate
   as of the date such litigation is filed.

4. Redistribution. You may reproduce and distribute copies of the
   Work or Derivative Works thereof in any medium, with or without
   modifications, and in Source or Object form, provided that You
   meet the following conditions:

   (a) You must give any other recipients of the Work or
       Derivative Works a copy of this License; and

   (b) You must cause any modified files to carry prominent notices
       stating that You changed the files; and

   (c) You must retain, in the Source form of any Derivative Works
       that You distribute, all copyright, patent, trademark, and
       attribution notices from the Source form of the Work,
       excluding those notices that do not pertain to any part of
       the Derivative Works; and

   (d) If the Work includes a "NOTICE" text file as part of its
       distribution, then any Derivative Works that You distribute must
       include a readable copy of the attribution notices contained
       within such NOTICE file, excluding those notices that do not
       pertain to any part of the Derivative Works, in at least one
       of the following places: within a NOTICE text file distributed
       as part of the Derivative Works; within the Source form or
       documentation, if provided along with the Derivative Works; or,
       within a display generated by the Derivative Works, if and
       wherever such third-party notices normally appear. The contents
       of the NOTICE file are for informational purposes only and
       do not modify the License. You may add Your own attribution
       notices within Derivative Works that You distribute, alongside
       or as an addendum to the NOTICE text from the Work, provided
       that such additional attribution notices cannot be construed
       as modifying the License.

   You may add Your own copyright statement to Your modifications and
   may provide additional or different license terms and conditions
   for use, reproduction, or distribution of Your modifications, or
   for any such Derivative Works as a whole, provided Your use,
   reproduction, and distribution of the Work otherwise complies with
   the conditions stated in this License.

5. Submission of Contributions. Unless You explicitly state otherwise,
   any Contribution intentionally submitted for inclusion in the Work
   by You to the Licensor shall be under the terms and conditions of
   this License, without any additional terms or conditions.
   Notwithstanding the above, nothing herein shall supersede or modify
   the terms of any separate license agreement you may have executed
   with Licensor regarding such Contributions.

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor,
   except as required for reasonable and customary use in describing the
   origin of the Work and reproducing the content of the NOTICE file.

7. Disclaimer of Warranty. Unless required by applicable law or
   agreed to in writing, Licensor provides the Work (and each
   Contributor provides its Contributions) on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
   implied, including, without limitation, any warranties or conditions
   of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
   PARTICULAR PURPOSE. You are solely responsible for determining the
   appropriateness of using or redistributing the Work and assume any
   risks associated with Your exercise of permissions under this License.

8. Limitation of Liability. In no event and under no legal theory,
   whether in tort (including negligence), contract, or otherwise,
   unless required by applicable law (such as deliberate and grossly
   negligent acts) or agreed to in writing, shall any Contributor be
   liable to You for damages, including any direct, indirect, special,
   incidental, or consequential damages of any character arising as a
   result of this License or out of the use or inability to use the
   Work (including but not limited to damages for loss of goodwill,
   work stoppage, computer failure or malfunction, or any and all
   other commercial damages or losses), even if such Contributor
   has been advised of the possibility of such damages.

9. Accepting Warranty or Additional Liability. While redistributing
   the Work or Derivative Works thereof, You may choose to offer,
   and charge a fee for, acceptance of support, warranty, indemnity,
   or other liability obligations and/or rights consistent with this
   License. However, in accepting such obligations, You may act only
   on Your own behalf and on Your sole responsibility, not on behalf
   of any other Contributor, and only if You agree to indemnify,
   defend, and hold each Contributor harmless for any liability
   incurred by, or claims asserted against, such Contributor by reason
   of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

   To apply the Apache License to your work, attach the following
   boilerplate notice, with the fields enclosed by brackets "[]"
   replaced with your own identifying information. (Don't include
   the brackets!)  The text should be enclosed in the appropriate
   comment syntax for the file format. We also recommend that a
   file or class name and description of purpose be included on the
   same "printed page" as the copyright notice for easier
   identification within third-party archives.

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


================================================
FILE: erased-serde-json/LICENSE-MIT
================================================
Copyright (c) 2014 The Rust Project Developers

Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.


================================================
FILE: erased-serde-json/README.md
================================================
Inspired by https://github.com/dtolnay/erased-serde

# erased-serde-json [![Crates.io](https://img.shields.io/crates/v/erased_serde_json.svg)](https://crates.io/crates/erased_serde_json) [![Crates.io](https://img.shields.io/crates/d/erased_serde_json.svg)](https://github.com/sevagh/pq/tree/master/erased-serde-json)

A helper crate for pq.


================================================
FILE: erased-serde-json/src/lib.rs
================================================
extern crate serde;
extern crate serde_json;

pub use self::ser::Formatter;

pub mod ser;


================================================
FILE: erased-serde-json/src/ser.rs
================================================
use std::io;

use serde_json::ser::CharEscape;

pub trait Formatter {
    fn erased_write_null(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_write_bool(
        &mut self,
        writer: &mut dyn io::Write,
        value: bool,
    ) -> Result<(), io::Error>;
    fn erased_write_i8(&mut self, writer: &mut dyn io::Write, value: i8) -> Result<(), io::Error>;
    fn erased_write_i16(&mut self, writer: &mut dyn io::Write, value: i16)
        -> Result<(), io::Error>;
    fn erased_write_i32(&mut self, writer: &mut dyn io::Write, value: i32)
        -> Result<(), io::Error>;
    fn erased_write_i64(&mut self, writer: &mut dyn io::Write, value: i64)
        -> Result<(), io::Error>;
    fn erased_write_u8(&mut self, writer: &mut dyn io::Write, value: u8) -> Result<(), io::Error>;
    fn erased_write_u16(&mut self, writer: &mut dyn io::Write, value: u16)
        -> Result<(), io::Error>;
    fn erased_write_u32(&mut self, writer: &mut dyn io::Write, value: u32)
        -> Result<(), io::Error>;
    fn erased_write_u64(&mut self, writer: &mut dyn io::Write, value: u64)
        -> Result<(), io::Error>;
    fn erased_write_f32(&mut self, writer: &mut dyn io::Write, value: f32)
        -> Result<(), io::Error>;
    fn erased_write_f64(&mut self, writer: &mut dyn io::Write, value: f64)
        -> Result<(), io::Error>;
    fn erased_begin_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_end_string(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_write_string_fragment(
        &mut self,
        writer: &mut dyn io::Write,
        fragment: &str,
    ) -> Result<(), io::Error>;
    fn erased_write_char_escape(
        &mut self,
        writer: &mut dyn io::Write,
        char_escape: CharEscape,
    ) -> Result<(), io::Error>;
    fn erased_begin_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_end_array(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_begin_array_value(
        &mut self,
        writer: &mut dyn io::Write,
        first: bool,
    ) -> Result<(), io::Error>;
    fn erased_end_array_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_begin_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_end_object(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_begin_object_key(
        &mut self,
        writer: &mut dyn io::Write,
        first: bool,
    ) -> Result<(), io::Error>;
    fn erased_end_object_key(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_begin_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
    fn erased_end_object_value(&mut self, writer: &mut dyn io::Write) -> Result<(), io::Error>;
}

impl<T> Formatter for T
where
    T: serde_json::ser::Formatter,
{
    fn erased_write_null(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.write_null(w)
    }
    fn erased_write_bool(&mut self, w: &mut dyn io::Write, v: bool) -> Result<(), io::Error> {
        self.write_bool(w, v)
    }
    fn erased_write_i8(&mut self, w: &mut dyn io::Write, v: i8) -> Result<(), io::Error> {
        self.write_i8(w, v)
    }
    fn erased_write_i16(&mut self, w: &mut dyn io::Write, v: i16) -> Result<(), io::Error> {
        self.write_i16(w, v)
    }
    fn erased_write_i32(&mut self, w: &mut dyn io::Write, v: i32) -> Result<(), io::Error> {
        self.write_i32(w, v)
    }
    fn erased_write_i64(&mut self, w: &mut dyn io::Write, v: i64) -> Result<(), io::Error> {
        self.write_i64(w, v)
    }
    fn erased_write_u8(&mut self, w: &mut dyn io::Write, v: u8) -> Result<(), io::Error> {
        self.write_u8(w, v)
    }
    fn erased_write_u16(&mut self, w: &mut dyn io::Write, v: u16) -> Result<(), io::Error> {
        self.write_u16(w, v)
    }
    fn erased_write_u32(&mut self, w: &mut dyn io::Write, v: u32) -> Result<(), io::Error> {
        self.write_u32(w, v)
    }
    fn erased_write_u64(&mut self, w: &mut dyn io::Write, v: u64) -> Result<(), io::Error> {
        self.write_u64(w, v)
    }
    fn erased_write_f32(&mut self, w: &mut dyn io::Write, v: f32) -> Result<(), io::Error> {
        self.write_f32(w, v)
    }
    fn erased_write_f64(&mut self, w: &mut dyn io::Write, v: f64) -> Result<(), io::Error> {
        self.write_f64(w, v)
    }
    fn erased_begin_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.begin_string(w)
    }
    fn erased_end_string(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_string(w)
    }
    fn erased_write_string_fragment(
        &mut self,
        w: &mut dyn io::Write,
        fragment: &str,
    ) -> Result<(), io::Error> {
        self.write_string_fragment(w, fragment)
    }
    fn erased_write_char_escape(
        &mut self,
        w: &mut dyn io::Write,
        char_escape: CharEscape,
    ) -> Result<(), io::Error> {
        self.write_char_escape(w, char_escape)
    }
    fn erased_begin_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.begin_array(w)
    }
    fn erased_end_array(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_array(w)
    }
    fn erased_begin_array_value(
        &mut self,
        w: &mut dyn io::Write,
        first: bool,
    ) -> Result<(), io::Error> {
        self.begin_array_value(w, first)
    }
    fn erased_end_array_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_array_value(w)
    }
    fn erased_begin_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.begin_object(w)
    }
    fn erased_end_object(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_object(w)
    }
    fn erased_begin_object_key(
        &mut self,
        w: &mut dyn io::Write,
        first: bool,
    ) -> Result<(), io::Error> {
        self.begin_object_key(w, first)
    }
    fn erased_end_object_key(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_object_key(w)
    }
    fn erased_begin_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.begin_object_value(w)
    }
    fn erased_end_object_value(&mut self, w: &mut dyn io::Write) -> Result<(), io::Error> {
        self.end_object_value(w)
    }
}

macro_rules! impl_formatter_for_trait_object {
    ($ty:ty) => {
        impl<'a> serde_json::ser::Formatter for $ty {
            fn write_null<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_write_null(&mut w)
            }
            fn write_bool<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: bool,
            ) -> Result<(), io::Error> {
                self.erased_write_bool(&mut w, v)
            }
            fn write_i8<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: i8,
            ) -> Result<(), io::Error> {
                self.erased_write_i8(&mut w, v)
            }
            fn write_i16<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: i16,
            ) -> Result<(), io::Error> {
                self.erased_write_i16(&mut w, v)
            }
            fn write_i32<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: i32,
            ) -> Result<(), io::Error> {
                self.erased_write_i32(&mut w, v)
            }
            fn write_i64<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: i64,
            ) -> Result<(), io::Error> {
                self.erased_write_i64(&mut w, v)
            }
            fn write_u8<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: u8,
            ) -> Result<(), io::Error> {
                self.erased_write_u8(&mut w, v)
            }
            fn write_u16<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: u16,
            ) -> Result<(), io::Error> {
                self.erased_write_u16(&mut w, v)
            }
            fn write_u32<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: u32,
            ) -> Result<(), io::Error> {
                self.erased_write_u32(&mut w, v)
            }
            fn write_u64<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: u64,
            ) -> Result<(), io::Error> {
                self.erased_write_u64(&mut w, v)
            }
            fn write_f32<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: f32,
            ) -> Result<(), io::Error> {
                self.erased_write_f32(&mut w, v)
            }
            fn write_f64<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                v: f64,
            ) -> Result<(), io::Error> {
                self.erased_write_f64(&mut w, v)
            }
            fn begin_string<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_begin_string(&mut w)
            }
            fn end_string<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_end_string(&mut w)
            }
            fn write_string_fragment<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                fragment: &str,
            ) -> Result<(), io::Error> {
                self.erased_write_string_fragment(&mut w, fragment)
            }
            fn write_char_escape<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                char_escape: CharEscape,
            ) -> Result<(), io::Error> {
                self.erased_write_char_escape(&mut w, char_escape)
            }
            fn begin_array<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_begin_array(&mut w)
            }
            fn end_array<W: ?Sized + io::Write>(&mut self, mut w: &mut W) -> Result<(), io::Error> {
                self.erased_end_array(&mut w)
            }
            fn begin_array_value<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                first: bool,
            ) -> Result<(), io::Error> {
                self.erased_begin_array_value(&mut w, first)
            }
            fn end_array_value<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_end_array_value(&mut w)
            }
            fn begin_object<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_begin_object(&mut w)
            }
            fn end_object<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_end_object(&mut w)
            }
            fn begin_object_key<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
                first: bool,
            ) -> Result<(), io::Error> {
                self.erased_begin_object_key(&mut w, first)
            }
            fn end_object_key<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_end_object_key(&mut w)
            }
            fn begin_object_value<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_begin_object_value(&mut w)
            }
            fn end_object_value<W: ?Sized + io::Write>(
                &mut self,
                mut w: &mut W,
            ) -> Result<(), io::Error> {
                self.erased_end_object_value(&mut w)
            }
        }
    };
}

impl_formatter_for_trait_object!(dyn Formatter);
impl_formatter_for_trait_object!(&'a mut dyn Formatter);
impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send));
impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Sync));
impl_formatter_for_trait_object!(&'a mut (dyn Formatter + Send + Sync));


================================================
FILE: src/commands.rs
================================================
use clap::ArgMatches;
use protobuf::descriptor::FileDescriptorSet;
use serde_json::ser::Serializer;

use std::io::{self, Write};
use std::path::PathBuf;

use crate::decode::PqDecoder;
use crate::discovery::{compile_descriptors_from_proto, get_loaded_descriptors};
use crate::formatter::CustomFormatter;

use stream_delimit::byte_consumer::ByteConsumer;
use stream_delimit::converter::Converter;
use stream_delimit::stream::*;

pub struct CommandRunner {
    descriptors: Vec<FileDescriptorSet>,
    prettyjson: bool,
}

#[cfg(feature = "default")]
use stream_delimit::kafka_consumer::KafkaConsumer;

impl CommandRunner {
    pub fn new(
        additional_fdset_dirs: Vec<PathBuf>,
        mut additional_fdset_files: Vec<PathBuf>,
        additional_proto_file: Option<&str>,
        prettyjson: bool,
    ) -> Self {
        if let Some(x) = additional_proto_file {
            let compiled_descriptor_path = compile_descriptors_from_proto(x);
            additional_fdset_files.push(compiled_descriptor_path);
        }

        let descriptors = get_loaded_descriptors(additional_fdset_dirs, additional_fdset_files);

        CommandRunner {
            descriptors,
            prettyjson,
        }
    }

    #[cfg(feature = "default")]
    pub fn run_kafka(self, matches: &ArgMatches<'_>) {
        if let (Some(brokers), Some(topic)) =
            (matches.value_of("BROKERS"), matches.value_of("TOPIC"))
        {
            let consumer = match KafkaConsumer::new(brokers, topic, matches.is_present("FROMBEG")) {
                Ok(x) => x,
                Err(e) => panic!("Couldn't initialize kafka consumer: {}", e),
            };
            decode_or_convert(consumer, matches, self.descriptors, self.prettyjson).unwrap();
        } else {
            panic!("Kafka needs broker[s] and topic");
        }
    }

    #[cfg(not(feature = "default"))]
    pub fn run_kafka(self, _: &ArgMatches) {
        unimplemented!("This version of pq has been compiled without kafka support");
    }

    pub fn run_byte(self, matches: &ArgMatches<'_>) {
        if unsafe { libc::isatty(0) != 0 } {
            panic!("pq expects input to be piped from stdin");
        }
        let stream_type = str_to_streamtype(matches.value_of("STREAM").unwrap_or("single"))
            .expect("Couldn't convert str to streamtype");
        decode_or_convert(
            ByteConsumer::new(io::stdin(), stream_type),
            matches,
            self.descriptors,
            self.prettyjson,
        )
        .unwrap()
    }
}

fn decode_or_convert<T: Iterator<Item = Vec<u8>> + FramedRead>(
    mut consumer: T,
    matches: &ArgMatches<'_>,
    descriptors: Vec<FileDescriptorSet>,
    prettyjson: bool,
) -> io::Result<()> {
    let count = value_t!(matches, "COUNT", i32).unwrap_or(-1);

    let stdout = io::stdout();

    let use_pretty_json = if prettyjson {
        prettyjson
    } else {
        unsafe { libc::isatty(1) != 0 }
    };
    if let Some(convert_type) = matches.value_of("CONVERT") {
        let converter = Converter::new(
            &mut consumer,
            str_to_streamtype(convert_type).expect("Couldn't convert str to streamtype"),
        );
        let stdout_ = &mut stdout.lock();
        for (ctr, item) in converter.enumerate() {
            if count >= 0 && ctr >= count as usize {
                break;
            }
            stdout_.write_all(&item).expect("Couldn't write to stdout");
        }
        Ok(())
    } else {
        let msgtype = format!(
            ".{}",
            matches
                .value_of("MSGTYPE")
                .expect("Must supply --msgtype or --convert")
        );

        let decoder = PqDecoder::new(descriptors, &msgtype);
        let mut formatter = CustomFormatter::new(use_pretty_json);
        let stdout_ = stdout.lock();
        let mut serializer = Serializer::with_formatter(stdout_, &mut formatter);
        let mut buffer = Vec::new();
        let mut ctr = 0;
        while let Some(item) = consumer.read_next_frame(&mut buffer)? {
            if count >= 0 && ctr >= count {
                break;
            }
            ctr += 1;
            decoder.transcode_message(item, &mut serializer);
        }
        Ok(())
    }
}


================================================
FILE: src/decode.rs
================================================
use protobuf::descriptor::FileDescriptorSet;
use protobuf::CodedInputStream;
use serde::Serializer;

use serde_protobuf::de::Deserializer;
use serde_protobuf::descriptor::Descriptors;

pub struct PqDecoder<'a> {
    pub descriptors: Descriptors,
    pub message_type: &'a str,
}

impl<'a> PqDecoder<'a> {
    pub fn new(loaded_descs: Vec<FileDescriptorSet>, message_type: &str) -> PqDecoder<'_> {
        let mut descriptors = Descriptors::new();
        for fdset in loaded_descs {
            descriptors.add_file_set_proto(&fdset);
        }
        descriptors.resolve_refs();
        PqDecoder {
            descriptors,
            message_type,
        }
    }

    pub fn transcode_message<S: Serializer>(&self, data: &[u8], out: S) {
        let stream = CodedInputStream::from_bytes(data);
        let mut deserializer =
            Deserializer::for_named_message(&self.descriptors, self.message_type, stream)
                .expect("could not init deserializer");

        serde_transcode::transcode(&mut deserializer, out).unwrap();
    }
}


================================================
FILE: src/discovery.rs
================================================
use protobuf::descriptor::FileDescriptorSet;
use protobuf::parse_from_reader;
use std::{
    env,
    fs::{read_dir, File},
    path::{Path, PathBuf},
    process::Command,
};

pub fn get_loaded_descriptors(
    additional_fdset_dirs: Vec<PathBuf>,
    mut additional_fdset_files: Vec<PathBuf>,
) -> Vec<FileDescriptorSet> {
    let (mut fdsets, mut tested_things) = discover_fdsets(additional_fdset_dirs);
    fdsets.append(&mut additional_fdset_files);
    tested_things.append(
        &mut additional_fdset_files
            .iter()
            .map(|x| format!("File: {:?}", x))
            .collect::<Vec<_>>(),
    );

    let mut descriptors: Vec<FileDescriptorSet> = Vec::new();

    for fdset_path in fdsets {
        let mut fdset_file = match File::open(fdset_path.as_path()) {
            Ok(x) => x,
            Err(e) => panic!("Couldn't open fdset file: {}", e),
        };
        match parse_from_reader(&mut fdset_file) {
            Err(_) => continue,
            Ok(x) => descriptors.push(x),
        }
    }

    if descriptors.is_empty() {
        panic!("No valid fdset files found. Checked: {:#?}", tested_things);
    }
    descriptors
}

fn discover_fdsets(additional_fdset_dirs: Vec<PathBuf>) -> (Vec<PathBuf>, Vec<String>) {
    let mut tested_things = Vec::new();
    let mut fdset_files = Vec::new();

    if let Ok(x) = env::var("FDSET_PATH") {
        tested_things.push(format!("Directory: {:?}", x));
        let p = PathBuf::from(x);
        fdset_files.append(&mut get_fdset_files_from_path(&p));
    }

    if let Some(mut x) = dirs::home_dir() {
        x.push(".pq");
        tested_things.push(format!("Directory: {:?}", x));
        fdset_files.append(&mut get_fdset_files_from_path(&x));
    }

    for x in additional_fdset_dirs {
        tested_things.push(format!("Directory: {:?}", x));
        fdset_files.append(&mut get_fdset_files_from_path(&x));
    }

    let x = PathBuf::from("/etc/pq");
    tested_things.push(format!("Directory: {:?}", x));
    fdset_files.append(&mut get_fdset_files_from_path(&x));

    (fdset_files, tested_things)
}

pub fn compile_descriptors_from_proto(proto_file: &str) -> PathBuf {
    let fdset_path = env::temp_dir().join("tmp-pq.fdset");

    let mut cmd = Command::new(protoc());
    cmd.arg("--include_imports")
        .arg("--include_source_info")
        .arg("-o")
        .arg(&fdset_path)
        .arg(proto_file);

    cmd.arg("-I").arg(protoc_include());

    let output = cmd.output().expect("failed to execute protoc");
    if !output.status.success() {
        panic!("protoc failed: {}", String::from_utf8_lossy(&output.stderr));
    }

    fdset_path
}

fn get_fdset_files_from_path(path: &Path) -> Vec<PathBuf> {
    let mut ret = vec![];
    if let Ok(paths) = read_dir(path) {
        for p in paths {
            let path = p.expect("error iterating through paths").path();
            if !path.is_dir() {
                ret.push(path);
            }
        }
    }
    ret
}

fn protoc() -> PathBuf {
    match env::var_os("PROTOC") {
        Some(protoc) => PathBuf::from(protoc),
        None => PathBuf::from(default_env!("PROTOC", "protoc")),
    }
}

fn protoc_include() -> PathBuf {
    match env::var_os("PROTOC_INCLUDE") {
        Some(include) => PathBuf::from(include),
        None => PathBuf::from(default_env!("PROTOC_INCLUDE", "")),
    }
}


================================================
FILE: src/formatter.rs
================================================
use erased_serde_json::Formatter as ErasedFormatter;
use serde_json::ser::{CompactFormatter, Formatter, PrettyFormatter};
use std::boxed::Box;
use std::io::{self, Write};

pub struct CustomFormatter {
    formatter: Box<dyn ErasedFormatter>,
    depth: usize,
}

impl CustomFormatter {
    pub fn new(use_pretty_json: bool) -> Self {
        let f: Box<dyn ErasedFormatter> = if use_pretty_json {
            Box::<PrettyFormatter<'_>>::default()
        } else {
            Box::new(CompactFormatter)
        };
        CustomFormatter {
            formatter: f,
            depth: 0,
        }
    }
}

impl<'a> Formatter for &'a mut CustomFormatter {
    fn begin_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.begin_array(w)
    }
    fn end_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.end_array(w)
    }
    fn begin_array_value<W: ?Sized + Write>(&mut self, w: &mut W, first: bool) -> io::Result<()> {
        self.formatter.begin_array_value(w, first)
    }
    fn end_array_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.end_array_value(w)
    }
    fn begin_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.depth += 1;
        self.formatter.begin_object(w)
    }
    fn end_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.end_object(w).and_then(|()| {
            self.depth -= 1;
            if self.depth == 0 {
                w.write_all(b"\n")
            } else {
                Ok(())
            }
        })
    }
    fn begin_object_key<W: ?Sized + Write>(&mut self, w: &mut W, first: bool) -> io::Result<()> {
        self.formatter.begin_object_key(w, first)
    }
    fn begin_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.begin_object_value(w)
    }
    fn end_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
        self.formatter.end_object_value(w)
    }
}


================================================
FILE: src/main.rs
================================================
#![crate_type = "bin"]

#[macro_use]
extern crate clap;

#[macro_use]
extern crate default_env;

mod commands;
mod decode;
mod discovery;
mod formatter;

use crate::commands::*;

fn main() {
    let matches = clap_app!(
        @app (app_from_crate!())
        (@arg MSGTYPE: --msgtype +takes_value +global conflicts_with[CONVERT]
            "Sets protobuf message type")
        (@arg STREAM: --stream +takes_value "Enables stream + sets stream type")
        (@arg COUNT: --count +takes_value +global "Stop after count messages")
        (@arg CONVERT: --convert +takes_value +global "Convert to different stream type")
        (@arg EXTRA_FDSET_DIRS: --fdsetdir +takes_value +global +multiple
             "[repeatable] Specify dirs to load fdset files from")
        (@arg EXTRA_FDSET_FILES: --fdsetfile +takes_value +global +multiple
             "[repeatable] Specify an fdset file")
        (@arg EXTRA_PROTO_FILE: --protofile +takes_value +global
             "Specify a proto file")
        (@arg PRETTY_JSON: --prettyjson +global
            "Force pretty json formatter. Default is pretty for a tty, otherwise compact")
        (@subcommand kafka =>
            (@arg TOPIC: +required "Sets the kafka topic")
            (@arg BROKERS: +required --brokers +takes_value "Comma-separated kafka brokers")
            (@arg FROMBEG: --beginning "Consume topic from beginning")
        )
    )
    .get_matches();

    let extra_fdset_dirs = match matches.values_of("EXTRA_FDSET_DIRS") {
        Some(dirs) => dirs.map(std::path::PathBuf::from).collect::<Vec<_>>(),
        None => vec![],
    };

    let extra_fdset_files = match matches.values_of("EXTRA_FDSET_FILES") {
        Some(files) => files.map(std::path::PathBuf::from).collect::<Vec<_>>(),
        None => vec![],
    };

    let extra_proto_file = matches.value_of("EXTRA_PROTO_FILE");
    let prettyjson = matches.is_present("PRETTY_JSON");

    let cmd = CommandRunner::new(
        extra_fdset_dirs,
        extra_fdset_files,
        extra_proto_file,
        prettyjson,
    );

    match matches.subcommand() {
        ("kafka", Some(m)) => cmd.run_kafka(m),
        _ => cmd.run_byte(&matches),
    }
}


================================================
FILE: stream-delimit/Cargo.toml
================================================
[package]
name = "stream_delimit"
version = "0.5.7"
authors = ["Sevag Hanssian <sevag.hanssian@gmail.com>"]
description = "length delimited protobuf stream separator"
repository = "https://github.com/sevagh/pq/tree/master/stream_delimit"
documentation = "http://docs.rs/stream_delimit/"
readme = "README.md"
license = "MIT"
keywords = ["protobuf", "serde"]
edition = "2018"

[dependencies]
kafka = { version = "0.8", optional = true }
byteorder = "1.3"

[features]
default = []
with_kafka = ["kafka"]


================================================
FILE: stream-delimit/LICENSE
================================================
MIT License

Copyright (c) 2017 Sevag Hanssian

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: stream-delimit/README.md
================================================
# stream_delimit [![Crates.io](https://img.shields.io/crates/v/stream_delimit.svg)](https://crates.io/crates/stream_delimit) [![Crates.io](https://img.shields.io/crates/d/stream_delimit.svg)](https://github.com/sevagh/pq/tree/master/stream-delimit)

A helper crate for pq.


### Varints

https://developers.google.com/protocol-buffers/docs/encoding#varints


================================================
FILE: stream-delimit/src/byte_consumer.rs
================================================
#![deny(missing_docs)]

use crate::stream::*;
use crate::{error::StreamDelimitError, varint::decode_varint};
use byteorder::{BigEndian, ReadBytesExt};
use std::{
    io::{self, Read},
    num::NonZeroUsize,
};

/// A consumer for a byte stream
pub struct ByteConsumer<T: Read> {
    read: T,
    type_: StreamType,
}

impl<T: Read> ByteConsumer<T> {
    /// Return a ByteConsumer from for single messages, varint or leb128-delimited
    pub fn new(read: T, type_: StreamType) -> ByteConsumer<T> {
        ByteConsumer { read, type_ }
    }

    fn read_next_frame_length(&mut self) -> io::Result<Option<NonZeroUsize>> {
        let r = match self.type_ {
            StreamType::Leb128 | StreamType::Varint => decode_varint(&mut self.read)
                .map_err(|e| {
                    // For unified error handling we force everything into io::Error
                    match e {
                        StreamDelimitError::VarintDecodeError(i) => i,
                        e => io::Error::new(io::ErrorKind::InvalidData, format!("{}", e)),
                    }
                })
                .map(|v| NonZeroUsize::new(v as usize)),
            StreamType::I32BE => self
                .read
                .read_i32::<BigEndian>()
                .map(|v| NonZeroUsize::new(v as usize)),
            StreamType::Single => Ok(None),
        };

        // In the cases where we have hit the end of the stream, read_i32 will return UnexpectedEof
        // we treat this as no more data
        match r {
            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => Ok(None),
            a => a,
        }
    }
}

impl<T: Read> Iterator for ByteConsumer<T> {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut buffer = Vec::new();
        self.read_next_frame(&mut buffer).ok()??;
        Some(buffer)
    }
}

impl<T: Read> FramedRead for ByteConsumer<T> {
    fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Result<Option<&'a [u8]>> {
        let r = match self.read_next_frame_length()? {
            Some(length) => {
                buffer.clear();
                let mut take = (&mut self.read).take(length.get() as u64);
                take.read_to_end(buffer)?;
                Some(&buffer[..])
            }
            // the single stream type does not have a defined length, so read_next_frame_length will return None
            // and we catch that special case here
            None if self.type_ == StreamType::Single => {
                buffer.clear();
                if self.read.read_to_end(buffer)? > 0 {
                    Some(&buffer[..])
                } else {
                    None
                }
            }
            _ => None,
        };
        Ok(r)
    }
}


================================================
FILE: stream-delimit/src/converter.rs
================================================
#![deny(missing_docs)]

use crate::stream::*;
use crate::varint::encode_varint;

/// A Converter struct to convert from a stream iterator to another `StreamType`
/// Useful for example to dump Kafka messages to a varint-delimited text file
pub struct Converter<'a> {
    stream_src: &'a mut dyn Iterator<Item = Vec<u8>>,
    stream_dest: StreamType,
}

impl<'a> Converter<'a> {
    /// Return a converter from a stream iterator
    pub fn new<T: Iterator<Item = Vec<u8>>>(
        stream_src: &'a mut T,
        stream_dest: StreamType,
    ) -> Converter<'a> {
        Converter {
            stream_src,
            stream_dest,
        }
    }
}

impl<'a> Iterator for Converter<'a> {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Vec<u8>> {
        match self.stream_dest {
            StreamType::Varint | StreamType::Leb128 => match self.stream_src.next() {
                Some(ref mut x) => {
                    let mut lead_varint = encode_varint(x.len() as u64);
                    lead_varint.append(x);
                    Some(lead_varint)
                }
                None => None,
            },
            _ => unimplemented!(),
        }
    }
}


================================================
FILE: stream-delimit/src/error.rs
================================================
use std::error::Error;
use std::fmt;
use std::io;
use std::result;

pub type Result<T> = result::Result<T, StreamDelimitError>;

#[derive(Debug)]
pub enum StreamDelimitError {
    #[cfg(feature = "with_kafka")]
    KafkaInitializeError(::kafka::error::Error),
    VarintDecodeError(io::Error),
    InvalidStreamTypeError(String),
    VarintDecodeMaxBytesError,
}

impl fmt::Display for StreamDelimitError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            #[cfg(feature = "with_kafka")]
            StreamDelimitError::KafkaInitializeError(ref e) => {
                write!(f, "Couldn't initialize kafka consumer: {}", e)
            }
            StreamDelimitError::VarintDecodeError(ref e) => {
                write!(f, "Couldn't decode leading varint: {}", e)
            }
            StreamDelimitError::InvalidStreamTypeError(ref t) => write!(
                f,
                "Invalid stream type: {} (only support single,leb128,varint)",
                t
            ),
            StreamDelimitError::VarintDecodeMaxBytesError => {
                write!(f, "Exceeded max attempts to decode leading varint")
            }
        }
    }
}

impl Error for StreamDelimitError {
    fn description(&self) -> &str {
        match *self {
            #[cfg(feature = "with_kafka")]
            StreamDelimitError::KafkaInitializeError(_) => "couldn't initialize kafka consumer",
            StreamDelimitError::VarintDecodeError(_)
            | StreamDelimitError::VarintDecodeMaxBytesError => "couldn't decode leading varint",
            StreamDelimitError::InvalidStreamTypeError(_) => "invalid stream type",
        }
    }

    fn cause(&self) -> Option<&dyn Error> {
        match *self {
            #[cfg(feature = "with_kafka")]
            StreamDelimitError::KafkaInitializeError(ref e) => Some(e),
            StreamDelimitError::VarintDecodeError(ref e) => Some(e),
            StreamDelimitError::InvalidStreamTypeError(_)
            | StreamDelimitError::VarintDecodeMaxBytesError => None,
        }
    }
}


================================================
FILE: stream-delimit/src/kafka_consumer.rs
================================================
#![deny(missing_docs)]

use crate::error::*;
use crate::stream::FramedRead;
use kafka::consumer::{Consumer, FetchOffset};
use std::collections::VecDeque;

/// A consumer from Kafka
pub struct KafkaConsumer {
    consumer: Consumer,
    messages: VecDeque<Vec<u8>>,
}

impl FramedRead for KafkaConsumer {
    fn read_next_frame<'a>(
        &mut self,
        buffer: &'a mut Vec<u8>,
    ) -> std::io::Result<Option<&'a [u8]>> {
        let res = self.next().map(move |mut v| {
            std::mem::swap(&mut v, buffer);
            &buffer[..]
        });
        Ok(res)
    }
}

impl Iterator for KafkaConsumer {
    type Item = Vec<u8>;

    fn next(&mut self) -> Option<Vec<u8>> {
        if self.messages.is_empty() {
            let kafka_consumer = &mut self.consumer;
            loop {
                match kafka_consumer.poll() {
                    Ok(mss) => {
                        for ms in mss.iter() {
                            self.messages.append(
                                &mut ms
                                    .messages()
                                    .iter()
                                    .map(|z| z.value.to_vec())
                                    .collect::<VecDeque<_>>(),
                            );
                            kafka_consumer
                                .consume_messageset(ms)
                                .expect("Couldn't mark messageset as consumed");
                        }
                        kafka_consumer
                            .commit_consumed()
                            .expect("Couldn't commit consumption");
                        if !self.messages.is_empty() {
                            break;
                        }
                    }
                    Err(e) => {
                        eprintln!("{}", e);
                        return None;
                    }
                }
            }
        }
        self.messages.pop_front()
    }
}

impl KafkaConsumer {
    /// Return a KafkaConsumer with some basic kafka connection properties
    pub fn new(brokers: &str, topic: &str, from_beginning: bool) -> Result<KafkaConsumer> {
        let fetch_offset = if from_beginning {
            FetchOffset::Earliest
        } else {
            FetchOffset::Latest
        };
        match Consumer::from_hosts(
            brokers
                .split(',')
                .map(std::borrow::ToOwned::to_owned)
                .collect::<Vec<String>>(),
        )
        .with_topic(topic.to_owned())
        .with_fallback_offset(fetch_offset)
        .with_fetch_max_bytes_per_partition(1024 * 1024)
        .create()
        {
            Ok(consumer) => Ok(KafkaConsumer {
                consumer,
                messages: VecDeque::new(),
            }),
            Err(e) => Err(StreamDelimitError::KafkaInitializeError(e)),
        }
    }
}


================================================
FILE: stream-delimit/src/lib.rs
================================================
extern crate byteorder;
#[cfg(feature = "with_kafka")]
extern crate kafka;

mod varint;

pub mod error;

/// Utilities to consume from a byte stream
pub mod byte_consumer;

/// Utilities to convert between stream types
pub mod converter;

/// Define stream types
pub mod stream;

#[cfg(feature = "with_kafka")]
/// Utilities to consume from Kafka
pub mod kafka_consumer;


================================================
FILE: stream-delimit/src/stream.rs
================================================
#![deny(missing_docs)]

use std::io;

use crate::error::*;

/// An enum type for byte streams
#[derive(PartialEq, Eq)]
pub enum StreamType {
    /// Protobuf messages with leading length encoded in leb128
    Leb128,
    /// Protobuf messages with leading length encoded in varint
    Varint,
    /// Protobuf messages with leading length encoded as
    /// binary big endian 32-bit signed integer
    I32BE,
    /// Single protobuf messages with no separators/delimiters
    Single,
}

/// Convert &str to associated `StreamType`
pub fn str_to_streamtype(input: &str) -> Result<StreamType> {
    match input {
        "single" => Ok(StreamType::Single),
        "varint" => Ok(StreamType::Varint),
        "leb128" => Ok(StreamType::Leb128),
        "i32be" => Ok(StreamType::I32BE),
        _ => Err(StreamDelimitError::InvalidStreamTypeError(
            input.to_string(),
        )),
    }
}

/// A trait for a stream that can be read in clearly defined chunks
pub trait FramedRead {
    /// should read the next available frame into the provided buffer.
    /// clear() will be called before the buffer is filled
    fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Result<Option<&'a [u8]>>;
}


================================================
FILE: stream-delimit/src/varint.rs
================================================
#![deny(missing_docs)]

use crate::error::*;
use std::io::Read;

const VARINT_MAX_BYTES: usize = 10;

pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
    let mut varint_buf: Vec<u8> = Vec::new();
    for i in 0..VARINT_MAX_BYTES {
        varint_buf.push(0u8);
        match read.read_exact(&mut varint_buf[i..]) {
            Ok(_) => (),
            Err(e) => return Err(StreamDelimitError::VarintDecodeError(e)),
        }
        if (varint_buf[i] & 0x80) == 0 {
            let mut concat: u64 = 0;
            for (j, &byte) in varint_buf[..=i].iter().enumerate() {
                concat |= u64::from(byte & 0x7f) << (j * 7);
            }
            return Ok(concat);
        }
    }
    Err(StreamDelimitError::VarintDecodeMaxBytesError)
}

pub fn encode_varint(mut value: u64) -> Vec<u8> {
    let mut ret = vec![0u8; VARINT_MAX_BYTES];
    let mut n = 0;
    while value > 127 {
        ret[n] = 0x80 | (value & 0x7F) as u8;
        value >>= 7;
        n += 1
    }
    ret[n] = value as u8;
    n += 1;
    ret[0..n].to_vec()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_simple() {
        assert_eq!(
            1,
            decode_varint(&mut Cursor::new(encode_varint(1))).unwrap()
        );
    }

    #[test]
    fn test_two_byte_varint() {
        assert_eq!(
            300,
            decode_varint(&mut Cursor::new(encode_varint(300))).unwrap()
        );
    }

    #[test]
    fn test_decode_known_varint_bytes() {
        let cases: &[(u64, &[u8])] = &[
            (0, &[0x00]),
            (1, &[0x01]),
            (127, &[0x7f]),
            (128, &[0x80, 0x01]),
            (300, &[0xac, 0x02]),
            (16384, &[0x80, 0x80, 0x01]),
            (2097152, &[0x80, 0x80, 0x80, 0x01]),
            (u32::MAX as u64, &[0xff, 0xff, 0xff, 0xff, 0x0f]),
            (
                u64::MAX,
                &[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01],
            ),
        ];

        for &(expected, bytes) in cases {
            assert_eq!(expected, decode_varint(&mut Cursor::new(bytes)).unwrap());
        }
    }

    #[test]
    fn test_three_byte_varint() {
        // 16384 requires 3 bytes: 0x80 0x80 0x01
        // This would fail with the old buggy shift formula
        assert_eq!(
            16384,
            decode_varint(&mut Cursor::new(encode_varint(16384))).unwrap()
        );
        assert_eq!(
            100000,
            decode_varint(&mut Cursor::new(encode_varint(100000))).unwrap()
        );
    }

    #[test]
    fn test_four_byte_varint() {
        // 2097152 requires 4 bytes
        assert_eq!(
            2097152,
            decode_varint(&mut Cursor::new(encode_varint(2097152))).unwrap()
        );
        assert_eq!(
            10000000,
            decode_varint(&mut Cursor::new(encode_varint(10000000))).unwrap()
        );
    }

    #[test]
    fn test_large_varints() {
        assert_eq!(
            u32::MAX as u64,
            decode_varint(&mut Cursor::new(encode_varint(u32::MAX as u64))).unwrap()
        );
        assert_eq!(
            u64::MAX,
            decode_varint(&mut Cursor::new(encode_varint(u64::MAX))).unwrap()
        );
    }
}


================================================
FILE: tests/README.md
================================================
Samples and fdset files compiled from the tools in the https://github.com/sevagh/protobuf-test-utils repo.


================================================
FILE: tests/fdsets/cat.fdset
================================================

<
	cat.protocom.example.cat"
Cat
is_lazy (RisLazy

================================================
FILE: tests/fdsets/dog.fdset
================================================

m
	dog.protocom.example.dog"O
Dog
breed (	Rbreed
age (Rage 
temperament (	Rtemperament

================================================
FILE: tests/fdsets/person.fdset
================================================

P
person.protocom.example.person",
Person
name (	Rname
id (Rid

================================================
FILE: tests/fdsets-invalid/.gitignore
================================================
*
!.gitignore


================================================
FILE: tests/protos/dog.proto
================================================
package com.example.dog;

message Dog {
  required string breed = 1;
  required int32 age = 2;
  optional string temperament = 3;
}


================================================
FILE: tests/samples/bad
================================================
thisisnotprotobuf

================================================
FILE: tests/samples/dog
================================================

gsdexcited

================================================
FILE: tests/samples/dog_stream
================================================


rottweilerchill

================================================
FILE: tests/test_pqrs_bin.rs
================================================
use assert_cli;

use std::env;

fn get_test_dir(final_piece: &str) -> String {
    let mut cwd = env::current_dir().unwrap();
    cwd.push("tests");
    cwd.push(final_piece);
    String::from(cwd.to_str().unwrap())
}

#[test]
fn test_dog_decode() {
    assert_cli::Assert::main_binary()
        .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets")))
        .with_args(&["--msgtype=com.example.dog.Dog"])
        .stdin(include_str!("samples/dog"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}")
        .unwrap();
}

#[test]
fn test_dog_decode_stream() {
    assert_cli::Assert::main_binary()
        .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets")))
        .with_args(&["--msgtype=com.example.dog.Dog", "--stream=varint"])
        .stdin(include_str!("samples/dog_stream"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"breed\":\"rottweiler\",\"age\":2,\"temperament\":\"chill\"}")
        .unwrap();
}

#[test]
fn test_dog_decode_i32be_stream() {
    assert_cli::Assert::main_binary()
        .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets")))
        .with_args(&["--msgtype=com.example.dog.Dog", "--stream=i32be"])
        .stdin(include_str!("samples/dog_i32be_stream"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}")
        .unwrap();
}

#[test]
fn test_nonexistent_fdset_dir() {
    assert_cli::Assert::main_binary()
        .with_env(
            assert_cli::Environment::inherit()
                .insert("FDSET_PATH", get_test_dir("fdsets-doesnt-exist")),
        )
        .with_args(&["--msgtype=com.example.dog.Dog"])
        .stdin(include_str!("samples/dog"))
        .fails()
        .and()
        .stderr()
        .contains("No valid fdset files found. Checked:")
        .unwrap();
}

#[test]
fn test_no_fdset_files() {
    assert_cli::Assert::main_binary()
        .with_env(
            assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets-invalid")),
        )
        .with_args(&["--msgtype=com.example.dog.Dog"])
        .stdin(include_str!("samples/dog"))
        .fails()
        .and()
        .stderr()
        .contains("No valid fdset files found. Checked:")
        .unwrap();
}

#[test]
fn test_person_decode() {
    assert_cli::Assert::main_binary()
        .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets")))
        .with_args(&["--msgtype=com.example.person.Person"])
        .stdin(include_str!("samples/person"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"name\":\"khosrov\",\"id\":0}")
        .unwrap();
}

#[test]
fn test_bad_input() {
    assert_cli::Assert::main_binary()
        .with_env(assert_cli::Environment::inherit().insert("FDSET_PATH", get_test_dir("fdsets")))
        .with_args(&["--msgtype=com.example.dog.Dog"])
        .stdin(include_str!("samples/bad"))
        .fails()
        .and()
        .stderr()
        .contains("protobuf error")
        .unwrap();
}

#[test]
fn test_person_decode_with_command_line_fdset_dir() {
    assert_cli::Assert::main_binary()
        .with_args(&[
            "--msgtype=com.example.person.Person",
            &format!("--fdsetdir={0}", get_test_dir("fdsets")),
        ])
        .stdin(include_str!("samples/person"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"name\":\"khosrov\",\"id\":0}")
        .unwrap();
}

#[test]
fn test_person_decode_with_command_line_fdset_file() {
    assert_cli::Assert::main_binary()
        .with_args(&[
            "--msgtype=com.example.person.Person",
            &format!("--fdsetfile={0}", get_test_dir("fdsets/person.fdset")),
        ])
        .stdin(include_str!("samples/person"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"name\":\"khosrov\",\"id\":0}")
        .unwrap();
}

#[test]
fn test_no_args() {
    assert_cli::Assert::main_binary()
        .fails()
        .and()
        .stderr()
        .contains("No valid fdset files found")
        .unwrap();
}

#[test]
fn test_cat_noncanonical_decode() {
    assert_cli::Assert::main_binary()
        .with_args(&[
            "--msgtype=com.example.cat.Cat",
            &format!("--fdsetfile={0}", get_test_dir("fdsets/cat.fdset")),
        ])
        .stdin(include_str!("samples/cat"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"is_lazy\":false}")
        .unwrap();
}

#[test]
#[ignore]
fn test_cat_canonical_decode() {
    assert_cli::Assert::main_binary()
        .with_args(&[
            "--msgtype=com.example.cat.Cat",
            &format!("--fdsetfile={0}", get_test_dir("fdsets/cat.fdset")),
        ])
        .stdin(include_str!("samples/cat"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"isLazy\":false}")
        .unwrap();
}

#[test]
fn test_dog_decode_from_proto() {
    assert_cli::Assert::main_binary()
        .with_env(
            assert_cli::Environment::inherit().insert("PROTOC_INCLUDE", get_test_dir("protos")),
        )
        .with_args(&[
            "--msgtype=com.example.dog.Dog",
            &format!("--protofile={0}", get_test_dir("protos/dog.proto")),
        ])
        .stdin(include_str!("samples/dog"))
        .succeeds()
        .and()
        .stdout()
        .contains("{\"breed\":\"gsd\",\"age\":3,\"temperament\":\"excited\"}")
        .unwrap();
}


================================================
FILE: utils/.gitignore
================================================
*_pb2.py
*.fdset
__pycache__
*.pyc


================================================
FILE: utils/GNUmakefile
================================================
PROTOS := $(wildcard *.proto)
FDSETS := $(patsubst %.proto,%.fdset,$(PROTOS))

all: $(FDSETS)

py:
	@protoc --python_out . ./*.proto -I./

%.fdset: %.proto
	@protoc -o ./$@ ./$^ -I./

.PHONY: clean

clean:
	-rm -rf ./*.fdset ./*_pb2.py ./*_pb3.py __pycache__


================================================
FILE: utils/README.txt
================================================
Protobuf sample files and generators for pq testing.


================================================
FILE: utils/cat.proto
================================================
package com.example.cat;

message Cat {
  required bool is_lazy = 1;
}


================================================
FILE: utils/dog.proto
================================================
package com.example.dog;

message Dog {
  required string breed = 1;
  required int32 age = 2;
  optional string temperament = 3;
}


================================================
FILE: utils/person.proto
================================================
package com.example.person;

message Person {
  required string name = 1;
  required int32 id = 2;
}


================================================
FILE: utils/proto_encoder.py
================================================
#!/usr/bin/env python3

import dog_pb2
import person_pb2
import cat_pb2
import sys
import random
from google.protobuf.internal import encoder
from optparse import OptionParser


def single(msgtype, stream=False):
    if msgtype == "cat":
        obj = cat_pb2.Cat(is_lazy=bool(random.getrandbits(1)))
    elif msgtype == "dog":
        obj = dog_pb2.Dog(
            age=random.choice(range(0, 20)),
            breed=["rottweiler", "gsd", "poodle"][random.choice(range(0, 3))],
            temperament=["chill", "aggressive", "excited"][random.choice(range(0, 3))],
        )
    elif msgtype == "person":
        obj = person_pb2.Person(
            id=random.choice(range(0, 4)),
            name=["raffi", "khosrov", "vahaken"][random.choice(range(0, 3))],
        )
    else:
        usage()
    obj = obj.SerializeToString()
    varint_ = encoder._VarintBytes(len(obj)) if stream else b""
    sys.stdout.buffer.write(varint_ + obj)


def stream(msgtype, limit):
    for _ in range(limit):
        single(msgtype, stream=True)


def usage():
    print(
        "Usage: {0} <single|stream> <dog|person|cat>"
        " [--count c]".format(sys.argv[0]),
        file=sys.stderr,
    )
    sys.exit(1)


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("--count", dest="count", help="stream count", metavar="COUNT")
    (options, args) = parser.parse_args(args=sys.argv)
    if len(args) != 3:
        usage()

    if args[1] == "single":
        single(args[2])
    elif args[1] == "stream":
        stream(args[2], int(options.count))


================================================
FILE: utils/requirements.txt
================================================
protobuf
Download .txt
gitextract_tt0fh83e/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── Makefile
├── README.md
├── erased-serde-json/
│   ├── .gitignore
│   ├── Cargo.toml
│   ├── LICENSE-APACHE
│   ├── LICENSE-MIT
│   ├── README.md
│   └── src/
│       ├── lib.rs
│       └── ser.rs
├── src/
│   ├── commands.rs
│   ├── decode.rs
│   ├── discovery.rs
│   ├── formatter.rs
│   └── main.rs
├── stream-delimit/
│   ├── Cargo.toml
│   ├── LICENSE
│   ├── README.md
│   └── src/
│       ├── byte_consumer.rs
│       ├── converter.rs
│       ├── error.rs
│       ├── kafka_consumer.rs
│       ├── lib.rs
│       ├── stream.rs
│       └── varint.rs
├── tests/
│   ├── README.md
│   ├── fdsets/
│   │   ├── cat.fdset
│   │   ├── dog.fdset
│   │   └── person.fdset
│   ├── fdsets-invalid/
│   │   └── .gitignore
│   ├── protos/
│   │   └── dog.proto
│   ├── samples/
│   │   ├── bad
│   │   ├── cat
│   │   ├── dog
│   │   ├── dog_i32be_stream
│   │   ├── dog_stream
│   │   ├── person
│   │   └── person_stream
│   └── test_pqrs_bin.rs
└── utils/
    ├── .gitignore
    ├── GNUmakefile
    ├── README.txt
    ├── cat.proto
    ├── dog.proto
    ├── person.proto
    ├── proto_encoder.py
    └── requirements.txt
Download .txt
SYMBOL INDEX (130 symbols across 14 files)

FILE: erased-serde-json/src/ser.rs
  type Formatter (line 5) | pub trait Formatter {
    method erased_write_null (line 6) | fn erased_write_null(&mut self, writer: &mut dyn io::Write) -> Result<...
    method erased_write_bool (line 7) | fn erased_write_bool(
    method erased_write_i8 (line 12) | fn erased_write_i8(&mut self, writer: &mut dyn io::Write, value: i8) -...
    method erased_write_i16 (line 13) | fn erased_write_i16(&mut self, writer: &mut dyn io::Write, value: i16)
    method erased_write_i32 (line 15) | fn erased_write_i32(&mut self, writer: &mut dyn io::Write, value: i32)
    method erased_write_i64 (line 17) | fn erased_write_i64(&mut self, writer: &mut dyn io::Write, value: i64)
    method erased_write_u8 (line 19) | fn erased_write_u8(&mut self, writer: &mut dyn io::Write, value: u8) -...
    method erased_write_u16 (line 20) | fn erased_write_u16(&mut self, writer: &mut dyn io::Write, value: u16)
    method erased_write_u32 (line 22) | fn erased_write_u32(&mut self, writer: &mut dyn io::Write, value: u32)
    method erased_write_u64 (line 24) | fn erased_write_u64(&mut self, writer: &mut dyn io::Write, value: u64)
    method erased_write_f32 (line 26) | fn erased_write_f32(&mut self, writer: &mut dyn io::Write, value: f32)
    method erased_write_f64 (line 28) | fn erased_write_f64(&mut self, writer: &mut dyn io::Write, value: f64)
    method erased_begin_string (line 30) | fn erased_begin_string(&mut self, writer: &mut dyn io::Write) -> Resul...
    method erased_end_string (line 31) | fn erased_end_string(&mut self, writer: &mut dyn io::Write) -> Result<...
    method erased_write_string_fragment (line 32) | fn erased_write_string_fragment(
    method erased_write_char_escape (line 37) | fn erased_write_char_escape(
    method erased_begin_array (line 42) | fn erased_begin_array(&mut self, writer: &mut dyn io::Write) -> Result...
    method erased_end_array (line 43) | fn erased_end_array(&mut self, writer: &mut dyn io::Write) -> Result<(...
    method erased_begin_array_value (line 44) | fn erased_begin_array_value(
    method erased_end_array_value (line 49) | fn erased_end_array_value(&mut self, writer: &mut dyn io::Write) -> Re...
    method erased_begin_object (line 50) | fn erased_begin_object(&mut self, writer: &mut dyn io::Write) -> Resul...
    method erased_end_object (line 51) | fn erased_end_object(&mut self, writer: &mut dyn io::Write) -> Result<...
    method erased_begin_object_key (line 52) | fn erased_begin_object_key(
    method erased_end_object_key (line 57) | fn erased_end_object_key(&mut self, writer: &mut dyn io::Write) -> Res...
    method erased_begin_object_value (line 58) | fn erased_begin_object_value(&mut self, writer: &mut dyn io::Write) ->...
    method erased_end_object_value (line 59) | fn erased_end_object_value(&mut self, writer: &mut dyn io::Write) -> R...
    method erased_write_null (line 66) | fn erased_write_null(&mut self, w: &mut dyn io::Write) -> Result<(), i...
    method erased_write_bool (line 69) | fn erased_write_bool(&mut self, w: &mut dyn io::Write, v: bool) -> Res...
    method erased_write_i8 (line 72) | fn erased_write_i8(&mut self, w: &mut dyn io::Write, v: i8) -> Result<...
    method erased_write_i16 (line 75) | fn erased_write_i16(&mut self, w: &mut dyn io::Write, v: i16) -> Resul...
    method erased_write_i32 (line 78) | fn erased_write_i32(&mut self, w: &mut dyn io::Write, v: i32) -> Resul...
    method erased_write_i64 (line 81) | fn erased_write_i64(&mut self, w: &mut dyn io::Write, v: i64) -> Resul...
    method erased_write_u8 (line 84) | fn erased_write_u8(&mut self, w: &mut dyn io::Write, v: u8) -> Result<...
    method erased_write_u16 (line 87) | fn erased_write_u16(&mut self, w: &mut dyn io::Write, v: u16) -> Resul...
    method erased_write_u32 (line 90) | fn erased_write_u32(&mut self, w: &mut dyn io::Write, v: u32) -> Resul...
    method erased_write_u64 (line 93) | fn erased_write_u64(&mut self, w: &mut dyn io::Write, v: u64) -> Resul...
    method erased_write_f32 (line 96) | fn erased_write_f32(&mut self, w: &mut dyn io::Write, v: f32) -> Resul...
    method erased_write_f64 (line 99) | fn erased_write_f64(&mut self, w: &mut dyn io::Write, v: f64) -> Resul...
    method erased_begin_string (line 102) | fn erased_begin_string(&mut self, w: &mut dyn io::Write) -> Result<(),...
    method erased_end_string (line 105) | fn erased_end_string(&mut self, w: &mut dyn io::Write) -> Result<(), i...
    method erased_write_string_fragment (line 108) | fn erased_write_string_fragment(
    method erased_write_char_escape (line 115) | fn erased_write_char_escape(
    method erased_begin_array (line 122) | fn erased_begin_array(&mut self, w: &mut dyn io::Write) -> Result<(), ...
    method erased_end_array (line 125) | fn erased_end_array(&mut self, w: &mut dyn io::Write) -> Result<(), io...
    method erased_begin_array_value (line 128) | fn erased_begin_array_value(
    method erased_end_array_value (line 135) | fn erased_end_array_value(&mut self, w: &mut dyn io::Write) -> Result<...
    method erased_begin_object (line 138) | fn erased_begin_object(&mut self, w: &mut dyn io::Write) -> Result<(),...
    method erased_end_object (line 141) | fn erased_end_object(&mut self, w: &mut dyn io::Write) -> Result<(), i...
    method erased_begin_object_key (line 144) | fn erased_begin_object_key(
    method erased_end_object_key (line 151) | fn erased_end_object_key(&mut self, w: &mut dyn io::Write) -> Result<(...
    method erased_begin_object_value (line 154) | fn erased_begin_object_value(&mut self, w: &mut dyn io::Write) -> Resu...
    method erased_end_object_value (line 157) | fn erased_end_object_value(&mut self, w: &mut dyn io::Write) -> Result...

FILE: src/commands.rs
  type CommandRunner (line 16) | pub struct CommandRunner {
    method new (line 25) | pub fn new(
    method run_kafka (line 45) | pub fn run_kafka(self, matches: &ArgMatches<'_>) {
    method run_kafka (line 60) | pub fn run_kafka(self, _: &ArgMatches) {
    method run_byte (line 64) | pub fn run_byte(self, matches: &ArgMatches<'_>) {
  function decode_or_convert (line 80) | fn decode_or_convert<T: Iterator<Item = Vec<u8>> + FramedRead>(

FILE: src/decode.rs
  type PqDecoder (line 8) | pub struct PqDecoder<'a> {
  function new (line 14) | pub fn new(loaded_descs: Vec<FileDescriptorSet>, message_type: &str) -> ...
  function transcode_message (line 26) | pub fn transcode_message<S: Serializer>(&self, data: &[u8], out: S) {

FILE: src/discovery.rs
  function get_loaded_descriptors (line 10) | pub fn get_loaded_descriptors(
  function discover_fdsets (line 42) | fn discover_fdsets(additional_fdset_dirs: Vec<PathBuf>) -> (Vec<PathBuf>...
  function compile_descriptors_from_proto (line 70) | pub fn compile_descriptors_from_proto(proto_file: &str) -> PathBuf {
  function get_fdset_files_from_path (line 90) | fn get_fdset_files_from_path(path: &Path) -> Vec<PathBuf> {
  function protoc (line 103) | fn protoc() -> PathBuf {
  function protoc_include (line 110) | fn protoc_include() -> PathBuf {

FILE: src/formatter.rs
  type CustomFormatter (line 6) | pub struct CustomFormatter {
    method new (line 12) | pub fn new(use_pretty_json: bool) -> Self {
  method begin_array (line 26) | fn begin_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
  method end_array (line 29) | fn end_array<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
  method begin_array_value (line 32) | fn begin_array_value<W: ?Sized + Write>(&mut self, w: &mut W, first: boo...
  method end_array_value (line 35) | fn end_array_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Resul...
  method begin_object (line 38) | fn begin_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<(...
  method end_object (line 42) | fn end_object<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Result<()> {
  method begin_object_key (line 52) | fn begin_object_key<W: ?Sized + Write>(&mut self, w: &mut W, first: bool...
  method begin_object_value (line 55) | fn begin_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Re...
  method end_object_value (line 58) | fn end_object_value<W: ?Sized + Write>(&mut self, w: &mut W) -> io::Resu...

FILE: src/main.rs
  function main (line 16) | fn main() {

FILE: stream-delimit/src/byte_consumer.rs
  type ByteConsumer (line 12) | pub struct ByteConsumer<T: Read> {
  function new (line 19) | pub fn new(read: T, type_: StreamType) -> ByteConsumer<T> {
  function read_next_frame_length (line 23) | fn read_next_frame_length(&mut self) -> io::Result<Option<NonZeroUsize>> {
  type Item (line 51) | type Item = Vec<u8>;
  method next (line 53) | fn next(&mut self) -> Option<Self::Item> {
  method read_next_frame (line 61) | fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Result...

FILE: stream-delimit/src/converter.rs
  type Converter (line 8) | pub struct Converter<'a> {
  function new (line 15) | pub fn new<T: Iterator<Item = Vec<u8>>>(
  type Item (line 27) | type Item = Vec<u8>;
  method next (line 29) | fn next(&mut self) -> Option<Vec<u8>> {

FILE: stream-delimit/src/error.rs
  type Result (line 6) | pub type Result<T> = result::Result<T, StreamDelimitError>;
  type StreamDelimitError (line 9) | pub enum StreamDelimitError {
    method fmt (line 18) | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  method description (line 40) | fn description(&self) -> &str {
  method cause (line 50) | fn cause(&self) -> Option<&dyn Error> {

FILE: stream-delimit/src/kafka_consumer.rs
  type KafkaConsumer (line 9) | pub struct KafkaConsumer {
    method new (line 68) | pub fn new(brokers: &str, topic: &str, from_beginning: bool) -> Result...
  method read_next_frame (line 15) | fn read_next_frame<'a>(
  type Item (line 28) | type Item = Vec<u8>;
  method next (line 30) | fn next(&mut self) -> Option<Vec<u8>> {

FILE: stream-delimit/src/stream.rs
  type StreamType (line 9) | pub enum StreamType {
  function str_to_streamtype (line 22) | pub fn str_to_streamtype(input: &str) -> Result<StreamType> {
  type FramedRead (line 35) | pub trait FramedRead {
    method read_next_frame (line 38) | fn read_next_frame<'a>(&mut self, buffer: &'a mut Vec<u8>) -> io::Resu...

FILE: stream-delimit/src/varint.rs
  constant VARINT_MAX_BYTES (line 6) | const VARINT_MAX_BYTES: usize = 10;
  function decode_varint (line 8) | pub fn decode_varint(read: &mut dyn Read) -> Result<u64> {
  function encode_varint (line 27) | pub fn encode_varint(mut value: u64) -> Vec<u8> {
  function test_simple (line 46) | fn test_simple() {
  function test_two_byte_varint (line 54) | fn test_two_byte_varint() {
  function test_decode_known_varint_bytes (line 62) | fn test_decode_known_varint_bytes() {
  function test_three_byte_varint (line 84) | fn test_three_byte_varint() {
  function test_four_byte_varint (line 98) | fn test_four_byte_varint() {
  function test_large_varints (line 111) | fn test_large_varints() {

FILE: tests/test_pqrs_bin.rs
  function get_test_dir (line 5) | fn get_test_dir(final_piece: &str) -> String {
  function test_dog_decode (line 13) | fn test_dog_decode() {
  function test_dog_decode_stream (line 26) | fn test_dog_decode_stream() {
  function test_dog_decode_i32be_stream (line 39) | fn test_dog_decode_i32be_stream() {
  function test_nonexistent_fdset_dir (line 52) | fn test_nonexistent_fdset_dir() {
  function test_no_fdset_files (line 68) | fn test_no_fdset_files() {
  function test_person_decode (line 83) | fn test_person_decode() {
  function test_bad_input (line 96) | fn test_bad_input() {
  function test_person_decode_with_command_line_fdset_dir (line 109) | fn test_person_decode_with_command_line_fdset_dir() {
  function test_person_decode_with_command_line_fdset_file (line 124) | fn test_person_decode_with_command_line_fdset_file() {
  function test_no_args (line 139) | fn test_no_args() {
  function test_cat_noncanonical_decode (line 149) | fn test_cat_noncanonical_decode() {
  function test_cat_canonical_decode (line 165) | fn test_cat_canonical_decode() {
  function test_dog_decode_from_proto (line 180) | fn test_dog_decode_from_proto() {

FILE: utils/proto_encoder.py
  function single (line 12) | def single(msgtype, stream=False):
  function stream (line 33) | def stream(msgtype, limit):
  function usage (line 38) | def usage():
Condensed preview — 49 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (75K chars).
[
  {
    "path": ".gitignore",
    "chars": 32,
    "preview": "target\nrust\n*.tar.gz\n*~\n*.bk\npq\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 998,
    "preview": "[package]\nname = \"pq\"\nversion = \"1.4.4\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\ndescription = \"jq for pr"
  },
  {
    "path": "LICENSE",
    "chars": 1071,
    "preview": "MIT License\n\nCopyright (c) 2017 Sevag Hanssian\n\nPermission is hereby granted, free of charge, to any person obtaining a "
  },
  {
    "path": "Makefile",
    "chars": 923,
    "preview": "WORKSPACES=\"./\" \"./stream-delimit/\"\nDOCKER_BIN ?= docker\nDOCKER_IMAGE=docker.io/clux/muslrust\nDOCKER_ARGS=run -v $(PWD):"
  },
  {
    "path": "README.md",
    "chars": 3563,
    "preview": "# pq [![license](https://img.shields.io/github/license/sevagh/pq.svg)](https://github.com/sevagh/pq/blob/master/LICENSE)"
  },
  {
    "path": "erased-serde-json/.gitignore",
    "chars": 39,
    "preview": "target/\n**/*.rs.bk\n*.sw[po]\nCargo.lock\n"
  },
  {
    "path": "erased-serde-json/Cargo.toml",
    "chars": 581,
    "preview": "[package]\nname = \"erased_serde_json\"\nversion = \"0.1.3\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\nlicense ="
  },
  {
    "path": "erased-serde-json/LICENSE-APACHE",
    "chars": 10847,
    "preview": "                              Apache License\n                        Version 2.0, January 2004\n                     http"
  },
  {
    "path": "erased-serde-json/LICENSE-MIT",
    "chars": 1071,
    "preview": "Copyright (c) 2014 The Rust Project Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a "
  },
  {
    "path": "erased-serde-json/README.md",
    "chars": 341,
    "preview": "Inspired by https://github.com/dtolnay/erased-serde\n\n# erased-serde-json [![Crates.io](https://img.shields.io/crates/v/e"
  },
  {
    "path": "erased-serde-json/src/lib.rs",
    "chars": 90,
    "preview": "extern crate serde;\nextern crate serde_json;\n\npub use self::ser::Formatter;\n\npub mod ser;\n"
  },
  {
    "path": "erased-serde-json/src/ser.rs",
    "chars": 12899,
    "preview": "use std::io;\n\nuse serde_json::ser::CharEscape;\n\npub trait Formatter {\n    fn erased_write_null(&mut self, writer: &mut d"
  },
  {
    "path": "src/commands.rs",
    "chars": 4230,
    "preview": "use clap::ArgMatches;\nuse protobuf::descriptor::FileDescriptorSet;\nuse serde_json::ser::Serializer;\n\nuse std::io::{self,"
  },
  {
    "path": "src/decode.rs",
    "chars": 1055,
    "preview": "use protobuf::descriptor::FileDescriptorSet;\nuse protobuf::CodedInputStream;\nuse serde::Serializer;\n\nuse serde_protobuf:"
  },
  {
    "path": "src/discovery.rs",
    "chars": 3363,
    "preview": "use protobuf::descriptor::FileDescriptorSet;\nuse protobuf::parse_from_reader;\nuse std::{\n    env,\n    fs::{read_dir, Fil"
  },
  {
    "path": "src/formatter.rs",
    "chars": 2071,
    "preview": "use erased_serde_json::Formatter as ErasedFormatter;\nuse serde_json::ser::{CompactFormatter, Formatter, PrettyFormatter}"
  },
  {
    "path": "src/main.rs",
    "chars": 2181,
    "preview": "#![crate_type = \"bin\"]\n\n#[macro_use]\nextern crate clap;\n\n#[macro_use]\nextern crate default_env;\n\nmod commands;\nmod decod"
  },
  {
    "path": "stream-delimit/Cargo.toml",
    "chars": 501,
    "preview": "[package]\nname = \"stream_delimit\"\nversion = \"0.5.7\"\nauthors = [\"Sevag Hanssian <sevag.hanssian@gmail.com>\"]\ndescription "
  },
  {
    "path": "stream-delimit/LICENSE",
    "chars": 1071,
    "preview": "MIT License\n\nCopyright (c) 2017 Sevag Hanssian\n\nPermission is hereby granted, free of charge, to any person obtaining a "
  },
  {
    "path": "stream-delimit/README.md",
    "chars": 357,
    "preview": "# stream_delimit [![Crates.io](https://img.shields.io/crates/v/stream_delimit.svg)](https://crates.io/crates/stream_deli"
  },
  {
    "path": "stream-delimit/src/byte_consumer.rs",
    "chars": 2782,
    "preview": "#![deny(missing_docs)]\n\nuse crate::stream::*;\nuse crate::{error::StreamDelimitError, varint::decode_varint};\nuse byteord"
  },
  {
    "path": "stream-delimit/src/converter.rs",
    "chars": 1184,
    "preview": "#![deny(missing_docs)]\n\nuse crate::stream::*;\nuse crate::varint::encode_varint;\n\n/// A Converter struct to convert from "
  },
  {
    "path": "stream-delimit/src/error.rs",
    "chars": 2080,
    "preview": "use std::error::Error;\nuse std::fmt;\nuse std::io;\nuse std::result;\n\npub type Result<T> = result::Result<T, StreamDelimit"
  },
  {
    "path": "stream-delimit/src/kafka_consumer.rs",
    "chars": 2888,
    "preview": "#![deny(missing_docs)]\n\nuse crate::error::*;\nuse crate::stream::FramedRead;\nuse kafka::consumer::{Consumer, FetchOffset}"
  },
  {
    "path": "stream-delimit/src/lib.rs",
    "chars": 371,
    "preview": "extern crate byteorder;\n#[cfg(feature = \"with_kafka\")]\nextern crate kafka;\n\nmod varint;\n\npub mod error;\n\n/// Utilities t"
  },
  {
    "path": "stream-delimit/src/stream.rs",
    "chars": 1217,
    "preview": "#![deny(missing_docs)]\n\nuse std::io;\n\nuse crate::error::*;\n\n/// An enum type for byte streams\n#[derive(PartialEq, Eq)]\np"
  },
  {
    "path": "stream-delimit/src/varint.rs",
    "chars": 3230,
    "preview": "#![deny(missing_docs)]\n\nuse crate::error::*;\nuse std::io::Read;\n\nconst VARINT_MAX_BYTES: usize = 10;\n\npub fn decode_vari"
  },
  {
    "path": "tests/README.md",
    "chars": 107,
    "preview": "Samples and fdset files compiled from the tools in the https://github.com/sevagh/protobuf-test-utils repo.\n"
  },
  {
    "path": "tests/fdsets/cat.fdset",
    "chars": 62,
    "preview": "\n<\n\tcat.proto\u0012\u000fcom.example.cat\"\u001e\n\u0003Cat\u0012\u0017\n\u0007is_lazy\u0018\u0001 \u0002(\bR\u0006isLazy"
  },
  {
    "path": "tests/fdsets/dog.fdset",
    "chars": 111,
    "preview": "\nm\n\tdog.proto\u0012\u000fcom.example.dog\"O\n\u0003Dog\u0012\u0014\n\u0005breed\u0018\u0001 \u0002(\tR\u0005breed\u0012\u0010\n\u0003age\u0018\u0002 \u0002(\u0005R\u0003age\u0012 \n\u000btemperament\u0018\u0003 \u0002(\tR\u000btemperament"
  },
  {
    "path": "tests/fdsets/person.fdset",
    "chars": 82,
    "preview": "\nP\n\fperson.proto\u0012\u0012com.example.person\",\n\u0006Person\u0012\u0012\n\u0004name\u0018\u0001 \u0002(\tR\u0004name\u0012\u000e\n\u0002id\u0018\u0002 \u0002(\u0005R\u0002id"
  },
  {
    "path": "tests/fdsets-invalid/.gitignore",
    "chars": 14,
    "preview": "*\n!.gitignore\n"
  },
  {
    "path": "tests/protos/dog.proto",
    "chars": 132,
    "preview": "package com.example.dog;\n\nmessage Dog {\n  required string breed = 1;\n  required int32 age = 2;\n  optional string tempera"
  },
  {
    "path": "tests/samples/bad",
    "chars": 17,
    "preview": "thisisnotprotobuf"
  },
  {
    "path": "tests/samples/dog",
    "chars": 16,
    "preview": "\n\u0003gsd\u0010\u0003\u001a\u0007excited"
  },
  {
    "path": "tests/samples/dog_stream",
    "chars": 22,
    "preview": "\u0015\n\nrottweiler\u0010\u0002\u001a\u0005chill"
  },
  {
    "path": "tests/test_pqrs_bin.rs",
    "chars": 5637,
    "preview": "use assert_cli;\n\nuse std::env;\n\nfn get_test_dir(final_piece: &str) -> String {\n    let mut cwd = env::current_dir().unwr"
  },
  {
    "path": "utils/.gitignore",
    "chars": 35,
    "preview": "*_pb2.py\n*.fdset\n__pycache__\n*.pyc\n"
  },
  {
    "path": "utils/GNUmakefile",
    "chars": 259,
    "preview": "PROTOS := $(wildcard *.proto)\nFDSETS := $(patsubst %.proto,%.fdset,$(PROTOS))\n\nall: $(FDSETS)\n\npy:\n\t@protoc --python_out"
  },
  {
    "path": "utils/README.txt",
    "chars": 53,
    "preview": "Protobuf sample files and generators for pq testing.\n"
  },
  {
    "path": "utils/cat.proto",
    "chars": 71,
    "preview": "package com.example.cat;\n\nmessage Cat {\n  required bool is_lazy = 1;\n}\n"
  },
  {
    "path": "utils/dog.proto",
    "chars": 132,
    "preview": "package com.example.dog;\n\nmessage Dog {\n  required string breed = 1;\n  required int32 age = 2;\n  optional string tempera"
  },
  {
    "path": "utils/person.proto",
    "chars": 101,
    "preview": "package com.example.person;\n\nmessage Person {\n  required string name = 1;\n  required int32 id = 2;\n}\n"
  },
  {
    "path": "utils/proto_encoder.py",
    "chars": 1566,
    "preview": "#!/usr/bin/env python3\n\nimport dog_pb2\nimport person_pb2\nimport cat_pb2\nimport sys\nimport random\nfrom google.protobuf.in"
  },
  {
    "path": "utils/requirements.txt",
    "chars": 9,
    "preview": "protobuf\n"
  }
]

// ... and 4 more files (download for full content)

About this extraction

This page contains the full source code of the sevagh/pq GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 49 files (67.8 KB), approximately 18.4k tokens, and a symbol index with 130 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!