0

I'm trying to build a wrapper for a c library for windows and linux and have the problem that windows wants u32, while linux wants u64. currently my api always takes u32 know since it's easy to upcast to u64. However with Vec<32> I need to convert it via:

let unsafe_pages: Vec<bindings::size_t> = pages.iter().map(|&p| p as bindings::size_t).collect();

pages is a Vec<32>

is there an easier way to make the conversion without itering over the collection?

Christian Schmitt
  • 837
  • 16
  • 47
  • This is a duplicated question. FYI this could be helpful for you: https://stackoverflow.com/questions/48308759/how-do-i-convert-a-vect-to-a-vecu-without-copying-the-vector – moy2010 Aug 19 '21 at 09:06
  • @moy2010 I don't think this is a duplicate. The question you linked is about an in-place conversion between vectors of types with potentially the same memory representation. This question is about a conversion that inherently requires copying the data. – Sven Marnach Aug 19 '21 at 09:08
  • Well, this other question (https://stackoverflow.com/questions/59707349/cast-vector-of-i8-to-vector-of-u8-in-rust) is (I guess) exactly like the one from the OP, and it was flagged as duplicate and pointed to the question I linked before. – moy2010 Aug 19 '21 at 09:11
  • Not really. You can use `p as _` if you don't want to duplicate the type, but other than that yours is the right way to convert. – Jmb Aug 19 '21 at 09:11
  • @moy2010 both questions you linked concern types that have the same size for input and output. Here the input is `u32` and the output may be `u64` (depending on the platform), so they have different sizes. – Jmb Aug 19 '21 at 09:14
  • @Jmb, that's a good observation. I had not considered the size of the types. – moy2010 Aug 19 '21 at 09:17
  • really unfortunate, that size_t differs from platform to platform, heck I even had other things which did not work that well however some TryInto stuff fixed it (constants that never go beyond 10000 i32/u32 – Christian Schmitt Aug 20 '21 at 08:03

1 Answers1

2

No. You need to allocate twice the space on the heap to hold the new data, and you need to copy it there with twice the spacing. This requires iteration. Of course there could theoretically be a library function doing the iteration for you, but there isn't. Moreover, your code is already rather succinct, so there isn't much to improve. If you want to be slightly more succinct, you can replace either of the two occurrences of bindings::size_t with _.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841