Most elegant way to find a Struct in a BTreeSet


#1

Hello there,

I already tried it via IRC, but maybe, it’s a too subjective question for IRC.

I’ve written and keep writing an API (Diesel (Postgres), Nickel) in Rust. The API is doing a lot of financial calculations. In these calculations, I often search for parameters. The parameters are mostly bound to different presets, etc. So I got a BTreeSet of parameters, found for a unique preset_id. These parameters have boundaries, maybe the height of a container.
Example: I want to find a specific parameter that matches as a range the height of the container. There are a dozen parameters. Starting from height: 100 … ending with height: 1200 (delta of steps is 100). A container has height: 574. Now I want to find the parameter, that matches the container. As the parameter has a height_from property, I try to find parameter { height_from: 500 ...}.

So what’s the most elegant way to do this?

I’ve tried to represent this via a gist on playground, but as you can see, I just bloated the code up massively up, while trying to implement this via Trait:
https://play.rust-lang.org/?gist=8ecbd415ff2f41ce71bcb7c67a387d96&version=stable

In the past, I indexed the parameters via a BTreeMap. But that’s imho not possible, if I search for parameters with boundaries.

Thanks in advance!


#2

Can you round down the parameter value to the step and then look it up directly in a hashmap? So if your increment size is 100, then you have (574 - (574 % 100)) = 500. If increment is 200, it’s (574 - (574 % 200)) = 400. And so on.

I don’t see why you need an ordered set or map here. Am I missing something?


#3

While I said before, the delta of 100 is fixed, it isn’t. It was just a poor example.
The parameters can be freely defined. So the boundary of the parameter could also be 563. So I was talking about a range … As I need to get the parameter, where the container is matched in that boundaries. Rounding is than not an option.


#4

Ok, that wasn’t clear indeed and so I was confused why you were jumping through hoops.

You can make your commented out range code work if you impl Borrow<i32> for Container (returning the height value).


#5

Never thought, it will be that easy. Thanks a bunch.

https://play.rust-lang.org/?gist=33462736ea41be1cad6cb95bb980d5fb&version=stable