summaryrefslogtreecommitdiff
path: root/spec/ruby/core/array/pack/shared/string.rb
blob: 256c1c08e837c43a02f15c88d06b0446e2e98192 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# -*- encoding: binary -*-
describe :array_pack_string, shared: true do
  it "adds count bytes of a String to the output" do
    ["abc"].pack(pack_format(2)).should == "ab"
  end

  it "implicitly has a count of one when no count is specified" do
    ["abc"].pack(pack_format).should == "a"
  end

  it "does not add any bytes when the count is zero" do
    ["abc"].pack(pack_format(0)).should == ""
  end

  it "is not affected by a previous count modifier" do
    ["abcde", "defg"].pack(pack_format(3)+pack_format).should == "abcd"
  end

  it "raises an ArgumentError when the Array is empty" do
    lambda { [].pack(pack_format) }.should raise_error(ArgumentError)
  end

  it "raises an ArgumentError when the Array has too few elements" do
    lambda { ["a"].pack(pack_format(nil, 2)) }.should raise_error(ArgumentError)
  end

  it "calls #to_str to convert the element to a String" do
    obj = mock('pack string')
    obj.should_receive(:to_str).and_return("abc")

    [obj].pack(pack_format).should == "a"
  end

  it "raises a TypeError when the object does not respond to #to_str" do
    obj = mock("not a string")
    lambda { [obj].pack(pack_format) }.should raise_error(TypeError)
  end

  it "returns a string in encoding of common to the concatenated results" do
    f = pack_format("*")
    [ [["\u{3042 3044 3046 3048}", 0x2000B].pack(f+"U"),       Encoding::ASCII_8BIT],
      [["abcde\xd1", "\xFF\xFe\x81\x82"].pack(f+"u"),          Encoding::ASCII_8BIT],
      [["a".force_encoding("ascii"), "\xFF\xFe\x81\x82"].pack(f+"u"), Encoding::ASCII_8BIT],
      # under discussion [ruby-dev:37294]
      [["\u{3042 3044 3046 3048}", 1].pack(f+"N"),             Encoding::ASCII_8BIT]
    ].should be_computed_by(:encoding)
  end
end