Project

General

Profile

Actions

Feature #19245

open

Strict mode for Array#pack that doesn't silently truncate numbers that are too large for the given directive

Added by byroot (Jean Boussier) over 1 year ago. Updated over 1 year ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:111339]

Description

>> [256].pack("C").unpack1("C")
=> 0
>> [257].pack("C").unpack1("C")
=> 1

This is specified:

  it "encodes the least significant 32 bits of a negative number" do
    [ [[-0x0000_0021], "\xdf\xff\xff\xff"],
      [[-0x0000_4321], "\xdf\xbc\xff\xff"],
      [[-0x0065_4321], "\xdf\xbc\x9a\xff"],
      [[-0x7865_4321], "\xdf\xbc\x9a\x87"]
    ].should be_computed_by(:pack, pack_format())
  end

But not documented in Array#pack.

I think that in many case this may lead to silent bugs.

Possible solutions

We could have a strict version of pack, either pack(template, strict: true) or pack!(template).

Or alternatively if we think this is never a desired behavior, we could change pack to first warn on truncation and later raise.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0