tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

zstdpy (2211B)


      1 #!/usr/bin/env python3
      2 # This Source Code Form is subject to the terms of the Mozilla Public
      3 # License, v. 2.0. If a copy of the MPL was not distributed with this
      4 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
      5 
      6 """This script compresses and decompresses data using the zstandard compression
      7 format, as provided by the python-zstandard module.
      8 
      9 Data is provided on stdin and output on stdout."""
     10 
     11 import sys
     12 import zstandard
     13 from argparse import ArgumentParser
     14 
     15 
     16 def main(argv=None):
     17     parser = ArgumentParser(description=__doc__)
     18     parser.set_defaults(mode="compress")
     19     parser.add_argument(
     20         "-z",
     21         "--compress",
     22         dest="mode",
     23         action="store_const",
     24         const="compress",
     25         help="compress the data (this is the default)",
     26     )
     27     parser.add_argument(
     28         "-d",
     29         "--decompress",
     30         dest="mode",
     31         action="store_const",
     32         const="decompress",
     33         help="decompress the data",
     34     )
     35     parser.add_argument(
     36         "-T",
     37         "--threads",
     38         dest="threads",
     39         default=1,
     40         type=int,
     41         help="Compress using # working threads. If 0, use number of CPUs on the system. (default 1)",
     42     )
     43     parser.add_argument(
     44         "-l",
     45         "--level",
     46         dest="level",
     47         default=3,
     48         type=int,
     49         help="Compression level from 1-22 (default 3)",
     50     )
     51     parser.add_argument(
     52         "file",
     53         nargs="?",
     54         help="File to compress/decompress. Default is stdin.",
     55     )
     56 
     57     args = parser.parse_args(argv)
     58 
     59     # The zstd commandline tool uses 0 to specify number of threads equal to
     60     # the number of CPUs whereas the python module uses negative numbers to
     61     # flag this behavior. Emulate the zstd commandline utility's behavior here
     62     if args.threads == 0:
     63         args.threads = -1
     64 
     65     if args.file:
     66         in_file = open(args.file, "rb")
     67     else:
     68         in_file = sys.stdin.buffer
     69 
     70     if args.mode == "compress":
     71         ctx = zstandard.ZstdCompressor(level=args.level, threads=args.threads)
     72     elif args.mode == "decompress":
     73         ctx = zstandard.ZstdDecompressor()
     74 
     75     ctx.copy_stream(in_file, sys.stdout.buffer)
     76 
     77 
     78 if __name__ == "__main__":
     79     main()