Re: [PATCH v1]] lib/btree.c: optimise the code by previously getpos function

From: Andy Shevchenko
Date: Fri Apr 28 2017 - 12:40:45 EST


On Tue, Apr 11, 2017 at 9:53 AM, Leno Hou <lenohou@xxxxxxxxx> wrote:
> This patch optimized the code by previously getpos function call.
> Therefore, It's takes the convenience to understand logic of code.

Besides what Christoph told you (I agree with him, writing test suites
/ modules is quite good exercise for newbies) my 2 cents for below
code that you may consider in the future as a technique of cleaning
up,

> +static int getpos(struct btree_geo *geo, unsigned long *node,
> + unsigned long *key)
> +{

> + int i;

unsigned int i;

> +
> + for (i = 0; i < geo->no_pairs; i++) {
> + if (keycmp(geo, node, i, key) <= 0)

> + break;

Here you return directly
return i;

> + }

> + return i;

And here is the best to return negative error code instead, like

return -ENOENT;

> +}

> for ( ; height > 1; height--) {
> - for (i = 0; i < geo->no_pairs; i++)
> - if (keycmp(geo, node, i, key) <= 0)
> - break;

> + i = getpos(geo, node, key);
> if (i == geo->no_pairs)
> return NULL;

Taking above into consideration you may do

i = getpos(geo, node, key);
if (i < 0)
return NULL;

Rationale behind that:
1) getpos() return value may be directly used whenever we need return
code to return;
2) you hide implementation details in your helper function
(geo->no_pairs dereference).

Though here both of them kinda minors you may use such technique in
the future for more complex code.

--
With Best Regards,
Andy Shevchenko