@@ -258,16 +258,44 @@ impl Layout {
258258
259259 /// Creates a layout describing the record for `self` followed by
260260 /// `next`, including any necessary padding to ensure that `next`
261- /// will be properly aligned, but *no trailing padding*. Note that
262- /// the resulting layout will satisfy the alignment properties of
263- /// both `self` and `next`, in order to ensure field alignment.
261+ /// will be properly aligned, but *no trailing padding*. In order to
262+ /// match C representation layout, you should call `pad_to_align`
263+ /// after extending the layout with all fields.
264+ ///
265+ /// Note that the resulting layout will satisfy the alignment properties
266+ /// of both `self` and `next`, in order to ensure alignment of both parts.
264267 ///
265268 /// Returns `Ok((k, offset))`, where `k` is layout of the concatenated
266269 /// record and `offset` is the relative location, in bytes, of the
267270 /// start of the `next` embedded within the concatenated record
268271 /// (assuming that the record itself starts at offset 0).
269272 ///
270273 /// On arithmetic overflow, returns `LayoutErr`.
274+ ///
275+ /// # Examples
276+ ///
277+ /// To calculate the layout of a `#[repr(C)]` structure from its fields' layouts:
278+ ///
279+ /// ```rust
280+ /// # use std::alloc::{Layout, LayoutErr};
281+ /// pub fn repr_c(fields: &[Layout]) -> Result<(Layout, Vec<usize>), LayoutErr> {
282+ /// let mut offsets = Vec::new();
283+ /// let mut layout = Layout::from_size_align(0, 1)?;
284+ /// for &field in fields {
285+ /// let (new_layout, offset) = layout.extend(field)?;
286+ /// layout = new_layout;
287+ /// offsets.push(offset);
288+ /// }
289+ /// Ok((layout.pad_to_align(), offsets))
290+ /// }
291+ /// # // test that it works
292+ /// # #[repr(C)] struct S { a: u64, b: u32, c: u16, d: u32 }
293+ /// # let s = Layout::new::<S>();
294+ /// # let u16 = Layout::new::<u16>();
295+ /// # let u32 = Layout::new::<u32>();
296+ /// # let u64 = Layout::new::<u64>();
297+ /// # assert_eq!(repr_c(&[u64, u32, u16, u32]), Ok((s, vec![0, 8, 12, 16])));
298+ /// ```
271299 #[ stable( feature = "alloc_layout_manipulation" , since = "1.44.0" ) ]
272300 #[ inline]
273301 pub fn extend ( & self , next : Self ) -> Result < ( Self , usize ) , LayoutErr > {
0 commit comments