Skip to content

Commit

Permalink
win32/registry: Refine pack/unpack
Browse files Browse the repository at this point in the history
* Use 'J' for HANDLE.
* Use 'Q' for QWORD.
* Define template constants.
* Supply zero bytes in `unpackqw` as well as `unpackdw`.
* Use `String#unpack1`.
  • Loading branch information
nobu committed May 3, 2024
1 parent 9f8e87c commit 0b091e6
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions ext/win32/lib/win32/registry.rb
Expand Up @@ -254,30 +254,34 @@ def win64?
/^(?:x64|x86_64)/ =~ RUBY_PLATFORM
end

TEMPLATE_HANDLE = -'J<'

def packhandle(h)
win64? ? packqw(h) : packdw(h)
[h].pack(TEMPLATE_HANDLE)
end

def unpackhandle(h)
win64? ? unpackqw(h) : unpackdw(h)
(h + [0].pack(TEMPLATE_HANDLE)).unpack1(TEMPLATE_HANDLE)
end

TEMPLATE_DWORD = -'V'

def packdw(dw)
[dw].pack('V')
[dw].pack(TEMPLATE_DWORD)
end

def unpackdw(dw)
dw += [0].pack('V')
dw.unpack('V')[0]
(dw + [0].pack(TEMPLATE_DWORD)).unpack1(TEMPLATE_DWORD)
end

TEMPLATE_QWORD = -'Q<'

def packqw(qw)
[ qw & 0xFFFFFFFF, qw >> 32 ].pack('VV')
[qw].pack(TEMPLATE_QWORD)
end

def unpackqw(qw)
qw = qw.unpack('VV')
(qw[1] << 32) | qw[0]
(qw + [0].pack(TEMPLATE_QWORD)).unpack1(TEMPLATE_QWORD)
end

def make_wstr(str)
Expand Down Expand Up @@ -657,7 +661,7 @@ def read(name, *rtype)
when REG_DWORD
[ type, API.unpackdw(data) ]
when REG_DWORD_BIG_ENDIAN
[ type, data.unpack('N')[0] ]
[ type, data.unpack1('N') ]
when REG_QWORD
[ type, API.unpackqw(data) ]
else
Expand Down

0 comments on commit 0b091e6

Please sign in to comment.