@@ -197,6 +197,19 @@ Here is this algorithm described in pseudocode.
197
197
198
198
<!-- ignore: pseudocode -->
199
199
``` rust,ignore
200
+ /// Returns the amount of padding needed after `offset` to ensure that the
201
+ /// following address will be aligned to `alignment`.
202
+ fn padding_needed_for(offset: usize, alignment: usize) -> usize {
203
+ let misalignment = offset % alignment;
204
+ if misalignment > 0 {
205
+ // round up to next multiple of `alignment`
206
+ alignment - misalignment
207
+ } else {
208
+ // already a multiple of `alignment`
209
+ 0
210
+ }
211
+ }
212
+
200
213
struct.alignment = struct.fields().map(|field| field.alignment).max();
201
214
202
215
let current_offset = 0;
@@ -205,16 +218,24 @@ for field in struct.fields_in_declaration_order() {
205
218
// Increase the current offset so that it's a multiple of the alignment
206
219
// of this field. For the first field, this will always be zero.
207
220
// The skipped bytes are called padding bytes.
208
- current_offset += field.alignment % current_offset ;
221
+ current_offset += padding_needed_for(current_offset, field.alignment) ;
209
222
210
223
struct[field].offset = current_offset;
211
224
212
225
current_offset += field.size;
213
226
}
214
227
215
- struct.size = current_offset + current_offset % struct.alignment;
228
+ struct.size = current_offset + padding_needed_for( current_offset, struct.alignment) ;
216
229
```
217
230
231
+ <div class =" warning " >
232
+
233
+ Warning: This pseudocode uses a naive algorithm that ignores overflow issues for
234
+ the sake of clarity. To perform memory layout computations in actual code, use
235
+ [ ` Layout ` ] .
236
+
237
+ </div >
238
+
218
239
> Note: This algorithm can produce zero-sized structs. This differs from
219
240
> C where structs without data still have a size of one byte.
220
241
@@ -363,3 +384,4 @@ used with any other representation.
363
384
[ `C` ] : #the-c-representation
364
385
[ primitive representations ] : #primitive-representations
365
386
[ `transparent` ] : #the-transparent-representation
387
+ [ `Layout` ] : ../std/alloc/struct.Layout.html
0 commit comments