commit 7e4470112b9fb6b11624c48b8421a87e6af72dc8 Author: Karchnu Date: Fri Nov 13 19:09:22 2020 +0100 initial commit: cq, json-to-cbor, benchmark json vs cbor diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7feb27f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +lib +bin +shard.lock diff --git a/shard.yml b/shard.yml new file mode 100644 index 0000000..31ac4b0 --- /dev/null +++ b/shard.yml @@ -0,0 +1,23 @@ +name: cq +version: 0.1.0 + +authors: + - Karchnu + +description: | + CBOR Query program, similar to jq. + +targets: + cq: + main: src/cq.cr + json-to-cbor: + main: src/json-to-cbor.cr + bm-json-vs-cbor: + main: tests/json-vs-cbor.cr + +dependencies: + cbor: + branch: float16 + git: https://git.sr.ht/~karchnu/crystal-cbor + +license: ISC diff --git a/src/cq.cr b/src/cq.cr new file mode 100644 index 0000000..e3d127f --- /dev/null +++ b/src/cq.cr @@ -0,0 +1,34 @@ +require "cbor" + +if ARGV.size >= 1 && ARGV[0] == "-h" + puts "usage: cq < file.cbor" + puts "usage: cq [attribute] < file" + exit 0 +end + +data = CBOR::Decoder.new(STDIN).read_value + +if ARGV.size == 0 + pp data + exit 0 +end + +def dig(data, attribute : String) + case data + when Hash + if v = data[attribute]? + return v + end + else + STDERR.puts "attribute not found: #{attribute}" + return nil + end +end + +ARGV.each do |attribute| + current_data = data.clone + attribute.split(/[.]/).each do |attr| + current_data = dig current_data, attr + end + pp current_data +end diff --git a/src/json-to-cbor.cr b/src/json-to-cbor.cr new file mode 100644 index 0000000..b1b7eed --- /dev/null +++ b/src/json-to-cbor.cr @@ -0,0 +1,10 @@ +require "cbor" +require "json" + +if ARGV.size >= 1 + puts "usage: json-to-cbor < file.json > file.cbor" + exit 0 +end + +json_content = JSON.parse STDIN.gets_to_end +STDOUT.write json_content.to_cbor diff --git a/tests/json-vs-cbor.cr b/tests/json-vs-cbor.cr new file mode 100644 index 0000000..0f5ff1d --- /dev/null +++ b/tests/json-vs-cbor.cr @@ -0,0 +1,37 @@ +require "benchmark" +require "json" +require "cbor" + +if ARGV.size == 0 || ARGV[0] == "-h" + puts "usage: #{PROGRAM_NAME} json-file" + exit 0 +end + +json_file = ARGV[0] +cbor_file = ARGV[0].gsub("json", "cbor") + +json_content = File.read(json_file) +cbor_content = File.read(cbor_file).to_slice + +json_value = JSON.parse json_content +cbor_value = CBOR::Decoder.new(cbor_content).read_value + +Benchmark.ips do |bm| + bm.report("JSON.parse") do + _ = JSON.parse json_content + end + + bm.report("CBOR::Decoder.new(input).read_value") do + _ = CBOR::Decoder.new(cbor_content).read_value + end +end + +Benchmark.ips do |bm| + bm.report("to_json") do + _ = json_value.to_json + end + + bm.report("to_cbor") do + _ = cbor_value.to_cbor + end +end