string-keys-to-int: now usable.

string-keys-to-int
Karchnu 2020-11-30 04:31:05 +01:00
parent 15a94a1609
commit 795acc1d33
1 changed files with 59 additions and 8 deletions

View File

@ -1,10 +1,37 @@
require "cbor" require "cbor"
require "option_parser"
if ARGV.size >= 1 && ARGV[0] == "-h" #
puts "usage: cbor-from-string-to-int-hash-keys < file.cbor" # JSON format has a limitation on the type of hash keys: it has to be a string.
puts "usage: cbor-from-string-to-int-hash-keys [attribute] < file" # 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 exit 0
end end
end
def are_hash_keys_all_int?(data) def are_hash_keys_all_int?(data)
case d = data case d = data
@ -23,7 +50,19 @@ end
def change(data) def change(data)
# 1. change keys # 1. change keys
if are_hash_keys_all_int? data 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 end
# 2. dig # 2. dig
@ -34,6 +73,8 @@ def change(data)
change d[k] change d[k]
end end
end end
rescue e
STDERR.puts "something went wrong: #{e}"
end end
buffer = Bytes.new 1_000_000 # 1 MB buffer = Bytes.new 1_000_000 # 1 MB
@ -43,12 +84,22 @@ until STDIN.read(buffer) == 0
while data = decoder.read_value while data = decoder.read_value
break if data == 0 break if data == 0
# pp data if Context.print_data
puts "input data:"
pp data
end
change data change data
# STDOUT.write data.to_cbor if Context.print_data
# STDOUT.flush puts "output data:"
pp data
end
unless Context.do_nothing
STDOUT.write data.to_cbor
STDOUT.flush
end
end end
buffer = Bytes.new 1_000_000 # 1 MB buffer = Bytes.new 1_000_000 # 1 MB
end end