From 795acc1d3363a421152ce3f84a942f7b7d29c20e Mon Sep 17 00:00:00 2001 From: Karchnu Date: Mon, 30 Nov 2020 04:31:05 +0100 Subject: [PATCH] string-keys-to-int: now usable. --- src/string-keys-to-int.cr | 67 ++++++++++++++++++++++++++++++++++----- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/src/string-keys-to-int.cr b/src/string-keys-to-int.cr index 1bcc1c4..52b37e5 100644 --- a/src/string-keys-to-int.cr +++ b/src/string-keys-to-int.cr @@ -1,9 +1,36 @@ require "cbor" +require "option_parser" -if ARGV.size >= 1 && ARGV[0] == "-h" - puts "usage: cbor-from-string-to-int-hash-keys < file.cbor" - puts "usage: cbor-from-string-to-int-hash-keys [attribute] < file" - exit 0 +# +# JSON format has a limitation on the type of hash keys: it has to be a string. +# CBOR doesn't come with such limitation. +# string-keys-to-int: automatically converts string keys into integers, whenever all +# the keys in a hash can be converted. +# + +class Context + class_property do_nothing = false + class_property print_data = false +end + +OptionParser.parse do |parser| + parser.banner = "usage: string-keys-to-int < file.cbor" + + parser.on "-n", "--nothing", + "Do nothing, just print when keys would have been converted." do + Context.do_nothing = true + end + + parser.on "-p", "--print-data", + "Do nothing, print keys to convert, input and output data." do + Context.do_nothing = true + Context.print_data = true + end + + parser.on "-h", "--help", "Displays this help and exits." do + puts parser + exit 0 + end end def are_hash_keys_all_int?(data) @@ -23,7 +50,19 @@ end def change(data) # 1. change keys if are_hash_keys_all_int? data - puts "YES, DO IT, keys: #{data.as(Hash).keys}" + if Context.do_nothing + puts "keys to convert: #{data.as(Hash).keys}" + end + + # Do something + case d = data + when Hash + keys = d.keys + keys.each do |k| + d[k.as(String).to_i32] = d[k] + d.delete k + end + end end # 2. dig @@ -34,6 +73,8 @@ def change(data) change d[k] end end +rescue e + STDERR.puts "something went wrong: #{e}" end buffer = Bytes.new 1_000_000 # 1 MB @@ -43,12 +84,22 @@ until STDIN.read(buffer) == 0 while data = decoder.read_value break if data == 0 - # pp data + if Context.print_data + puts "input data:" + pp data + end change data - # STDOUT.write data.to_cbor - # STDOUT.flush + if Context.print_data + puts "output data:" + pp data + end + + unless Context.do_nothing + STDOUT.write data.to_cbor + STDOUT.flush + end end buffer = Bytes.new 1_000_000 # 1 MB end