Skip to content

Commit 2eb069f

Browse files
Avoid calling memcpy in swap (#5500)
Co-authored-by: Stephan T. Lavavej <[email protected]>
1 parent c6c64d3 commit 2eb069f

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

stl/inc/type_traits

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
#if _STL_COMPILER_PREPROCESSOR
1010
#include <cstddef>
1111
#include <cstdint>
12-
#include <cstring>
1312
#include <xtr1common>
1413

1514
#pragma pack(push, _CRT_PACKING)
@@ -2513,21 +2512,31 @@ void _Swap_trivial_arrays(_Ty (&_Left)[_Size], _Ty (&_Right)[_Size]) noexcept {
25132512
if constexpr (_Size_parts != 0) {
25142513
const auto _Stop = _Left_ptr + _Size_parts;
25152514
do {
2516-
unsigned char _Buf[_Part_size_bytes];
2517-
_CSTD memcpy(_Buf, _Left_ptr, _Part_size_bytes);
2518-
_CSTD memcpy(_Left_ptr, _Right_ptr, _Part_size_bytes);
2519-
_CSTD memcpy(_Right_ptr, _Buf, _Part_size_bytes);
2515+
struct _Buffer_type {
2516+
unsigned char _Data[_Part_size_bytes];
2517+
};
2518+
2519+
_STL_INTERNAL_STATIC_ASSERT(sizeof(_Buffer_type) == _Part_size_bytes); // assume no padding
2520+
2521+
const _Buffer_type _Buffer = *reinterpret_cast<const _Buffer_type*>(_Left_ptr);
2522+
*reinterpret_cast<_Buffer_type*>(_Left_ptr) = *reinterpret_cast<const _Buffer_type*>(_Right_ptr);
2523+
*reinterpret_cast<_Buffer_type*>(_Right_ptr) = _Buffer;
25202524
_Left_ptr += _Part_size_bytes;
25212525
_Right_ptr += _Part_size_bytes;
25222526

25232527
} while (_Left_ptr != _Stop);
25242528
}
25252529

25262530
if constexpr (_Size_tail != 0) {
2527-
unsigned char _Buf[_Size_tail];
2528-
_CSTD memcpy(_Buf, _Left_ptr, _Size_tail);
2529-
_CSTD memcpy(_Left_ptr, _Right_ptr, _Size_tail);
2530-
_CSTD memcpy(_Right_ptr, _Buf, _Size_tail);
2531+
struct _Last_buffer_type {
2532+
unsigned char _Data[_Size_tail];
2533+
};
2534+
2535+
_STL_INTERNAL_STATIC_ASSERT(sizeof(_Last_buffer_type) == _Size_tail); // assume no padding
2536+
2537+
const _Last_buffer_type _Last_buffer = *reinterpret_cast<const _Last_buffer_type*>(_Left_ptr);
2538+
*reinterpret_cast<_Last_buffer_type*>(_Left_ptr) = *reinterpret_cast<const _Last_buffer_type*>(_Right_ptr);
2539+
*reinterpret_cast<_Last_buffer_type*>(_Right_ptr) = _Last_buffer;
25312540
}
25322541
}
25332542

0 commit comments

Comments
 (0)