From 85867980e4446b54efba2bce08f0064fa1d93ade Mon Sep 17 00:00:00 2001 From: Matthew LeVan Date: Fri, 22 Nov 2024 09:44:32 -0500 Subject: [PATCH] Add `@q` --- lib/aura.rb | 1 + lib/aura/q.rb | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 lib/aura/q.rb diff --git a/lib/aura.rb b/lib/aura.rb index f13e48e..ac6d01a 100644 --- a/lib/aura.rb +++ b/lib/aura.rb @@ -2,6 +2,7 @@ require "aura/helpers" require "aura/p" +require "aura/q" require "hoon" require_relative "aura/version" diff --git a/lib/aura/q.rb b/lib/aura/q.rb new file mode 100644 index 0000000..b1f451d --- /dev/null +++ b/lib/aura/q.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative("helpers") +require_relative("../hoon") +require_relative("p") + +module Aura + # @q + module Q + extend Helpers + + module_function + + # Convert a number to a @q-encoded string. + def self.patq(arg) + n = arg.to_i + buf = n.to_s(16).scan(/../).map(&:hex) + puts buf + buf2patq(buf) + end + + def self.buf2patq(buf) + # Split the buffer into chunks of 2, with a special case for odd-length buffers + chunked = if buf.length.odd? && buf.length > 1 + [[buf[0]]] + buf[1..-1].each_slice(2).to_a + else + buf.each_slice(2).to_a + end + + chunked.reduce("~") do |acc, elem| + acc + (acc == "~" ? "" : "-") + alg(elem, chunked) + end + end + + def prefix_name(byts) + byts[1].nil? ? prefixes[0] + suffixes[byts[0]] : prefixes[byts[0]] + suffixes[byts[1]] + end + + def name(byts) + byts[1].nil? ? suffixes[byts[0]] : prefixes[byts[0]] + suffixes[byts[1]] + end + + def alg(pair, chunked) + pair.length.odd? && chunked.length > 1 ? prefix_name(pair) : name(pair) + end + end +end