Naming convention to distinguish conversion to `Vec<bool>` vs `Vec<u8>`

Normally one would use a naming convention like to_vec and into_vec when converting an object to a Vec<_>. However, I need to distinguish conversions to Vec<bool> and Vec<u8> as the semantics are different. Is there a canonical naming convention to handle this distinction?

  • to_vec_bool / to_vec_u8?
  • to_bool_vec / to_u8_vec?
  • to_bits? to_bytes? (Tempting, but contradicts the naming guide which associates bytes with &[u8].)

What do the two functions do?

This is for a bit vector representation (bitvec-rs).

  • Conversion into Vec<u8> (currently via into_vec) returns the underlying storage as that's the guaranteed underlying representation.
  • Conversion to Vec<bool> (newly added per user request) does the logical conversion from bits to bools.

I'll have to make a breaking change to rename into_vec to more clearly distinguish the two. My only concern is that the naming convention doesn't address this distinction.

I think it's much better to return impl Iterator<Item=bool> which allow callers to .collect() it to vector, instead of allocate new vector in library.

2 Likes

I think you should follow @Hyeonu's suggestion and make an iterator instead, that way you could potentially save an allocation and provide a more flexible api. The name of the function could be into_bits/to_bits depending on whether you wan't to consume or keep the old bitvector.

Another option is to IntoIterator for Bitvec and &BitVec that will allow the user to choose if they want to consume the BitVec. Then you only have into_vec which returns the underlying storage.

1 Like

Thanks. Indeed, I already have iterator implementations. I also just added size_hint and other overrides for the iterator, so that collect, as you suggested, should be more efficient now. Though now that you mention it @RustyYato, I am missing the IntoIterator implementations and I'll add them.

Nevertheless, the current into_vec does seem a little ambiguous now (underlying representation vs conversion to vector of bools). WDYT?

Would into_bytes work?

1 Like

Yeah, perhaps I should not overthink the seeming contradiction with the naming convention that I mentioned in the original post.

Thanks both for your feedback!

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.