string-keys-to-int: now usable.

This commit is contained in:
Karchnu 2020-11-30 04:31:05 +01:00
parent 15a94a1609
commit 795acc1d33

View File

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