From d0ee4f22839e49aaa7b394143c53c593bbd3cf11 Mon Sep 17 00:00:00 2001 From: Falk David Date: Mon, 9 Oct 2023 13:39:26 +0200 Subject: [PATCH] BLI: Support negative steps in `findlinkfrom` The function `BLI_findlinkfrom` returns the link that is n-steps after the given start link. This did not work for negative steps. This change makes it so that both positive and negative step values work. --- source/blender/blenlib/BLI_listbase.h | 5 +++-- source/blender/blenlib/intern/listbase.cc | 15 +++++++++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/source/blender/blenlib/BLI_listbase.h b/source/blender/blenlib/BLI_listbase.h index 394f5b23f5d..5cb1e5f3cab 100644 --- a/source/blender/blenlib/BLI_listbase.h +++ b/source/blender/blenlib/BLI_listbase.h @@ -45,9 +45,10 @@ void *BLI_findlink(const struct ListBase *listbase, int number) ATTR_WARN_UNUSED ATTR_NONNULL(1); /** - * Returns the nth element after \a link, numbering from 0. + * Returns the element before/after \a link that is \a step links away, numbering from 0. \a step + * is allowed to be negative. Returns NULL when the link is out-of-bounds. */ -void *BLI_findlinkfrom(struct Link *start, int number) ATTR_WARN_UNUSED_RESULT; +void *BLI_findlinkfrom(struct Link *start, int step) ATTR_WARN_UNUSED_RESULT; /** * Finds the first element of \a listbase which contains the null-terminated diff --git a/source/blender/blenlib/intern/listbase.cc b/source/blender/blenlib/intern/listbase.cc index 9af2634c5d3..8e0ddc6ebe5 100644 --- a/source/blender/blenlib/intern/listbase.cc +++ b/source/blender/blenlib/intern/listbase.cc @@ -560,17 +560,24 @@ void *BLI_rfindlink(const ListBase *listbase, int number) return link; } -void *BLI_findlinkfrom(Link *start, int number) +void *BLI_findlinkfrom(Link *start, int steps) { Link *link = nullptr; - if (number >= 0) { + if (steps >= 0) { link = start; - while (link != nullptr && number != 0) { - number--; + while (link != nullptr && steps != 0) { + steps--; link = link->next; } } + else { + link = start; + while (link != nullptr && steps != 0) { + steps++; + link = link->prev; + } + } return link; }