1begin
2  require_relative 'helper'
3  require 'fiddle/struct'
4rescue LoadError
5end
6
7module Fiddle
8  class TestCStructEntity < TestCase
9    def test_class_size
10      types = [TYPE_DOUBLE, TYPE_CHAR]
11
12      size = CStructEntity.size types
13
14      alignments = types.map { |type| PackInfo::ALIGN_MAP[type] }
15
16      expected = PackInfo.align 0, alignments[0]
17      expected += PackInfo::SIZE_MAP[TYPE_DOUBLE]
18
19      expected = PackInfo.align expected, alignments[1]
20      expected += PackInfo::SIZE_MAP[TYPE_CHAR]
21
22      expected = PackInfo.align expected, alignments.max
23
24      assert_equal expected, size
25    end
26
27    def test_class_size_with_count
28      size = CStructEntity.size([[TYPE_DOUBLE, 2], [TYPE_CHAR, 20]])
29
30      types = [TYPE_DOUBLE, TYPE_CHAR]
31      alignments = types.map { |type| PackInfo::ALIGN_MAP[type] }
32
33      expected = PackInfo.align 0, alignments[0]
34      expected += PackInfo::SIZE_MAP[TYPE_DOUBLE] * 2
35
36      expected = PackInfo.align expected, alignments[1]
37      expected += PackInfo::SIZE_MAP[TYPE_CHAR] * 20
38
39      expected = PackInfo.align expected, alignments.max
40
41      assert_equal expected, size
42    end
43
44    def test_set_ctypes
45      union = CStructEntity.malloc [TYPE_INT, TYPE_LONG]
46      union.assign_names %w[int long]
47
48      # this test is roundabout because the stored ctypes are not accessible
49      union['long'] = 1
50      union['int'] = 2
51
52      assert_equal 1, union['long']
53      assert_equal 2, union['int']
54    end
55
56    def test_aref_pointer_array
57      team = CStructEntity.malloc([[TYPE_VOIDP, 2]])
58      team.assign_names(["names"])
59      alice = Fiddle::Pointer.malloc(6)
60      alice[0, 6] = "Alice\0"
61      bob = Fiddle::Pointer.malloc(4)
62      bob[0, 4] = "Bob\0"
63      team["names"] = [alice, bob]
64      assert_equal(["Alice", "Bob"], team["names"].map(&:to_s))
65    end
66
67    def test_aref_pointer
68      user = CStructEntity.malloc([TYPE_VOIDP])
69      user.assign_names(["name"])
70      alice = Fiddle::Pointer.malloc(6)
71      alice[0, 6] = "Alice\0"
72      user["name"] = alice
73      assert_equal("Alice", user["name"].to_s)
74    end
75  end
76end if defined?(Fiddle)
77