[PATCH v5 09/20] media: rc: Use binary search for adding or updating a scancode

From: Sean Young

Date: Tue Sep 15 2026 - 04:58:08 EST


We can have up to 1024 scancodes entries which are always sorted, so make
this a little faster.

We need to either get an scancode entry, or find the insertion point
in the sorted array if no existing entry was found. The bsearch() function
cannot do this as it runs NULL is no matching entry is found. Therefore,
we provide an open coded binary search.

Signed-off-by: Sean Young <sean@xxxxxxxx>
---
drivers/media/rc/rc-main.c | 20 +++++++++++++-------
1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/drivers/media/rc/rc-main.c b/drivers/media/rc/rc-main.c
index 37ba19164875..ed746255b0a2 100644
--- a/drivers/media/rc/rc-main.c
+++ b/drivers/media/rc/rc-main.c
@@ -391,7 +391,7 @@ static unsigned int ir_establish_scancode(struct rc_dev *dev,
struct rc_map *rc_map,
u64 scancode, bool resize)
{
- unsigned int i;
+ unsigned int i, lo, hi;

lockdep_assert_held(&rc_map->lock);

@@ -406,15 +406,21 @@ static unsigned int ir_establish_scancode(struct rc_dev *dev,
if (dev->scancode_mask)
scancode &= dev->scancode_mask;

- /* First check if we already have a mapping for this ir command */
- for (i = 0; i < rc_map->len; i++) {
+ /*
+ * Binary search for an existing mapping for this ir command.
+ */
+ lo = 0;
+ hi = rc_map->len;
+ while (lo < hi) {
+ i = lo + (hi - lo) / 2;
if (rc_map->scan[i].scancode == scancode)
return i;
-
- /* Keytable is sorted from lowest to highest scancode */
- if (rc_map->scan[i].scancode >= scancode)
- break;
+ if (rc_map->scan[i].scancode < scancode)
+ lo = i + 1;
+ else
+ hi = i;
}
+ i = lo;

/* No previous mapping found, we might need to grow the table */
if (rc_map->size == rc_map->len) {
--
2.55.0