Recursion with class function

I’m writing small code to check an address belongs to a memory region (including cross region). I came up with idea using recursion function. Here is my code:


virtual class bit_utils#(WIDTH = 32);
  static function bit in_range(bit[WIDTH-1:0] val_a, bit[WIDTH-1:0] min_a, bit[WIDTH-1:0] max_a);
    if(min_a <= max_a) begin
      in_range = (val_a inside {[min_a:max_a]});
    end
    else begin
      in_range = in_range(val_a, min_a, {WIDTH{1'b1}}) || in_range(val_a, {WIDTH{1'b0}}, max_a);
    end
  endfunction
endclass



module top;
  initial begin
    // Check 8'FE belongs to [8'hFC : 8'h01]
    $display("in_range = %0d", bit_utils#(8)::in_range(8'hFE, 8'hFC, 8'h01));
  end
endmodule

It works. But I’m not sure it’s safety or not. Please help me clarify!
By the way, do you have any better to idea for this problem?

Thanks.

In reply to chris_le:
It’s safe. Even though you declared in_range as a static class method, its lifetime is automatic. Class methods always have automatic lifetimes, so arguments are always pushed on a stack frame.

But there is a much easier way of doing this without recursion:

virtual class bit_utils#(WIDTH = 32);
  static function bit in_range(bit[WIDTH-1:0] val_a, min_a, max_a);
    if(min_a <= max_a)
      return ( val_a inside {[min_a:max_a]} );
    else 
      return !(val_a inside {[max_a:min_a]} );
  endfunction
endclass

In reply to dave_59:

Thanks for detail explaination.
About your code, I think we should change:


virtual class bit_utils#(WIDTH = 32);
  static function bit in_range(bit[WIDTH-1:0] val_a, min_a, max_a);
    if(min_a <= max_a)
      return ( val_a inside {[min_a:max_a]} );
    else 
      // Include boundaries of the range
      return !(val_a inside {[max_a+1:min_a-1]} );
  endfunction
endclass

In reply to chris_le:

Agreed.