From 9044044c27c3619a18f58c8c235250264cd95a7e Mon Sep 17 00:00:00 2001 From: Simon Marchi Date: Sun, 9 Feb 2025 00:51:00 -0500 Subject: gdbsupport: add gdb::make_array_view overload to create from an array MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I think this overload will be useful for the following reasons. Consider a templated function like this: template void func(gdb::array_view view) {} Trying to pass an array to this function doesn't work, as template argument deduction fails: test.c:698:8: error: no matching function for call to ‘func(int [12])’ 698 | func (array); | ~~~~~^~~~~~~ test.c:686:6: note: candidate: ‘template void func(gdb::array_view)’ 686 | void func(gdb::array_view view) {} | ^~~~ test.c:686:6: note: template argument deduction/substitution failed: test.c:698:8: note: mismatched types ‘gdb::array_view’ and ‘int*’ 698 | func (array); | ~~~~~^~~~~~~ Similarly, trying to compare a view with an array doesn't work. This: int array[12]; gdb::array_view view; if (view == array) {} ... fails with: test.c:698:8: error: no matching function for call to ‘func(int [12])’ 698 | func (array); | ~~~~~^~~~~~~ test.c:686:6: note: candidate: ‘template void func(gdb::array_view)’ 686 | void func(gdb::array_view view) {} | ^~~~ test.c:686:6: note: template argument deduction/substitution failed: test.c:698:8: note: mismatched types ‘gdb::array_view’ and ‘int*’ 698 | func (array); | ~~~~~^~~~~~~ With this new overload, we can do: func (gdb::make_array_view (array)); and if (view == gdb::make_array_view (array)) {} This is not ideal, I wish that omitting `gdb::make_array_view` would just work, but at least it allows creating an array view and have the element type automatically deduced from the array type. If someone knows how to make these cases "just work", I would be happy to know how. Change-Id: I6a71919d2d5a385e6826801d53f5071b470fef5f Approved-By: Tom Tromey --- gdb/unittests/array-view-selftests.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'gdb') diff --git a/gdb/unittests/array-view-selftests.c b/gdb/unittests/array-view-selftests.c index c07b572..cc3fcfd 100644 --- a/gdb/unittests/array-view-selftests.c +++ b/gdb/unittests/array-view-selftests.c @@ -554,6 +554,19 @@ run_tests () SELF_CHECK (view[i] == data[i]); } + /* gdb::make_array_view with an array. */ + { + const gdb_byte data[] = {0x55, 0x66, 0x77, 0x88}; + const auto len = sizeof (data) / sizeof (data[0]); + const auto view = gdb::make_array_view (data); + + SELF_CHECK (view.data () == data); + SELF_CHECK (view.size () == len); + + for (std::size_t i = 0; i < len; ++i) + SELF_CHECK (view[i] == data[i]); + } + /* Test slicing. */ { gdb_byte data[] = {0x55, 0x66, 0x77, 0x88, 0x99}; -- cgit v1.1