@@ -168,7 +168,7 @@ const fn in_place_collectible<DEST, SRC>(
168
168
step_merge : Option < NonZeroUsize > ,
169
169
step_expand : Option < NonZeroUsize > ,
170
170
) -> bool {
171
- if DEST :: IS_ZST || mem:: align_of :: < SRC > ( ) < mem:: align_of :: < DEST > ( ) {
171
+ if const { SRC :: IS_ZST || DEST :: IS_ZST || mem:: align_of :: < SRC > ( ) < mem:: align_of :: < DEST > ( ) } {
172
172
return false ;
173
173
}
174
174
@@ -186,6 +186,27 @@ const fn in_place_collectible<DEST, SRC>(
186
186
}
187
187
}
188
188
189
+ const fn needs_realloc < SRC , DEST > ( src_cap : usize , dst_cap : usize ) -> bool {
190
+ if const { mem:: align_of :: < SRC > ( ) != mem:: align_of :: < DEST > ( ) } {
191
+ return src_cap > 0 ;
192
+ }
193
+
194
+ // If src type size is an integer multiple of the destination type size then
195
+ // the caller will have calculated a `dst_cap` that is an integer multiple of
196
+ // `src_cap` without remainder.
197
+ if const {
198
+ let src_sz = mem:: size_of :: < SRC > ( ) ;
199
+ let dest_sz = mem:: size_of :: < DEST > ( ) ;
200
+ dest_sz != 0 && src_sz % dest_sz == 0
201
+ } {
202
+ return false ;
203
+ }
204
+
205
+ // type layouts don't guarantee a fit, so do a runtime check to see if
206
+ // the allocations happen to match
207
+ return src_cap > 0 && src_cap * mem:: size_of :: < SRC > ( ) != dst_cap * mem:: size_of :: < DEST > ( ) ;
208
+ }
209
+
189
210
/// This provides a shorthand for the source type since local type aliases aren't a thing.
190
211
#[ rustc_specialization_trait]
191
212
trait InPlaceCollect : SourceIter < Source : AsVecIntoIter > + InPlaceIterable {
@@ -259,13 +280,10 @@ where
259
280
// that wasn't a multiple of the destination type size.
260
281
// Since the discrepancy should generally be small this should only result in some
261
282
// bookkeeping updates and no memmove.
262
- if ( const {
263
- let src_sz = mem:: size_of :: < I :: Src > ( ) ;
264
- src_sz > 0 && mem:: size_of :: < T > ( ) % src_sz != 0
265
- } && src_cap * mem:: size_of :: < I :: Src > ( ) != dst_cap * mem:: size_of :: < T > ( ) )
266
- || const { mem:: align_of :: < T > ( ) != mem:: align_of :: < I :: Src > ( ) }
267
- {
283
+ if needs_realloc :: < I :: Src , T > ( src_cap, dst_cap) {
268
284
let alloc = Global ;
285
+ debug_assert_ne ! ( src_cap, 0 ) ;
286
+ debug_assert_ne ! ( dst_cap, 0 ) ;
269
287
unsafe {
270
288
// The old allocation exists, therefore it must have a valid layout.
271
289
let src_align = mem:: align_of :: < I :: Src > ( ) ;
@@ -286,6 +304,8 @@ where
286
304
let Ok ( reallocated) = result else { handle_alloc_error ( new_layout) } ;
287
305
dst_buf = reallocated. as_ptr ( ) as * mut T ;
288
306
}
307
+ } else {
308
+ debug_assert_eq ! ( src_cap * mem:: size_of:: <I :: Src >( ) , dst_cap * mem:: size_of:: <T >( ) ) ;
289
309
}
290
310
291
311
mem:: forget ( dst_guard) ;
0 commit comments