initial commit: cq, json-to-cbor, benchmark json vs cbor

master
Karchnu 2020-11-13 19:09:22 +01:00
commit 7e4470112b
5 changed files with 107 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
lib
bin
shard.lock

23
shard.yml Normal file
View File

@ -0,0 +1,23 @@
name: cq
version: 0.1.0
authors:
- Karchnu <karchnu@karchnu.fr>
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

34
src/cq.cr Normal file
View File

@ -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

10
src/json-to-cbor.cr Normal file
View File

@ -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

37
tests/json-vs-cbor.cr Normal file
View File

@ -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