dimanche 28 avril 2019

How should I insert a value into the "middle" of another

I have two values v1 and v2 of types T1 and T2 respectively, with sizeof(T1)>sizeof(T2). Both types are plain-old-data. Now, I want to replace the k'th, k+1'th, ... k+sizeof(T2)-1'th bytes of v1 with the bytes of v2.

C++ doesn't offer this functionality inherently in the language, nor to my knowledge in the standard library (at least, not directly). What would be the best approach to implementing this generically? i.e. implementing:

template<typename T1, typename T2>
T1 replace_bytes(T1 v1, T2 v2, std::size_t k)

or

template<typename T1, typename T2>
void replace_bytes(T1& v1, T2 v2, std::size_t k)

?

My thoughts have been:

  1. Reinterpret cast into arrays of bytes
  2. Reinterpret cast into std::array of bytes
  3. Use spans
  4. Pointer arithmetic with the address of v1
  5. For not-so-large types - reinterpret as unsigned integers and use bit operations: AND with a mask, shift, OR to combine the existing and replacement bits.

Notes:

  • You may assume for the sake of simplicity that memory layout is little-endian.
  • If alignment is an issue, be explicit about your choices regarding it.
  • Efficiency/speed is of course a key issue.
  • If your suggestion requires a newer C++ language standard, that's fine, but do mention it.

Aucun commentaire:

Enregistrer un commentaire