bytes icon indicating copy to clipboard operation
bytes copied to clipboard

Add `Bytes::try_slice` method

Open al8n opened this issue 1 month ago • 5 comments

Hi, will it be acceptable to add a try_slice method? Currently, having to copy the bounds check logic before invoking the Bytes::slice.

al8n avatar Nov 23 '25 04:11 al8n

Also having to manually check bounds with split_to and split_off. Looks like slice_ref also has the same type of behavior.

Would love a provided try_* set of methods.

Will-Low avatar Dec 01 '25 23:12 Will-Low

I think functions like try_slice and try_split_to are not commonly used. It makes more sense for downstream users to perform manual checks. Bypassing such checks and relying on external libraries seems unusual to me.

ADD-SP avatar Dec 02 '25 12:12 ADD-SP

On the one hand, it's quite easy to check this without bytes adding anything. And I suspect it's quite common that you've already checked the length at some point before reaching to slice (this matches my experience). I'm also a fan of a smaller public APIs, and not providing things just in case, but when needed.

However, when I look at libstd, the slice primitive does have Option returning methods:

  • slice.get(0..10)
  • slice.split_at_checked(10)
  • slice.split_off(10)

Personally, I think they messed up the naming, probably as these variants were added separately.

If we want to provide these, I'd suggest they all be try_*.

seanmonstar avatar Dec 02 '25 13:12 seanmonstar

On the one hand, it's quite easy to check this without bytes adding anything. And I suspect it's quite common that you've already checked the length at some point before reaching to slice (this matches my experience). I'm also a fan of a smaller public APIs, and not providing things just in case, but when needed.

However, when I look at libstd, the slice primitive does have Option returning methods:

  • slice.get(0..10)
  • slice.split_at_checked(10)
  • slice.split_off(10)

Personally, I think they messed up the naming, probably as these variants were added separately.

If we want to provide these, I'd suggest they all be try_*.

For length, yes, commonly checked. However, slice does not only check length, but also range bounds. When the public API depends on Bytes accepting a Range* as a parameter, then the fn has to copy the whole bounds checking logic.

al8n avatar Dec 02 '25 20:12 al8n

I think functions like try_slice and try_split_to are not commonly used. It makes more sense for downstream users to perform manual checks. Bypassing such checks and relying on external libraries seems unusual to me.

I do not think so. It is quite commonly used when you want to develop a no-panic library, especially in embedded programming.

al8n avatar Dec 02 '25 20:12 al8n