diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 39ef641a3ace2..470749ef7b338 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -8,10 +8,12 @@ use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::DefId; use rustc_middle::middle::stability; +use rustc_middle::span_bug; use rustc_middle::ty::layout::LayoutError; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{Adt, TyCtxt}; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_target::abi::{Layout, Primitive, TagEncoding, Variants}; use super::{ collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_strs, notable_traits_decl, @@ -1621,6 +1623,15 @@ fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) { } fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) { + fn write_size_of_layout(w: &mut Buffer, layout: &Layout, tag_size: u64) { + if layout.abi.is_unsized() { + write!(w, "(unsized)"); + } else { + let bytes = layout.size.bytes() - tag_size; + write!(w, "{size} byte{pl}", size = bytes, pl = if bytes == 1 { "" } else { "s" },); + } + } + if !cx.shared.show_type_layout { return; } @@ -1642,16 +1653,40 @@ fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) { “Type Layout” \ chapter for details on type layout guarantees.

" ); - if ty_layout.layout.abi.is_unsized() { - writeln!(w, "

Size: (unsized)

"); - } else { - let bytes = ty_layout.layout.size.bytes(); - writeln!( - w, - "

Size: {size} byte{pl}

", - size = bytes, - pl = if bytes == 1 { "" } else { "s" }, - ); + w.write_str("

Size: "); + write_size_of_layout(w, ty_layout.layout, 0); + writeln!(w, "

"); + if let Variants::Multiple { variants, tag, tag_encoding, .. } = + &ty_layout.layout.variants + { + if !variants.is_empty() { + w.write_str( + "

Size for each variant:

\ + "); + } } } // This kind of layout error can occur with valid code, e.g. if you try to diff --git a/src/test/rustdoc/type-layout.rs b/src/test/rustdoc/type-layout.rs index 272911de6815b..0868486fa59cd 100644 --- a/src/test/rustdoc/type-layout.rs +++ b/src/test/rustdoc/type-layout.rs @@ -52,3 +52,21 @@ pub struct Unsized([u8]); // @!has type_layout/trait.MyTrait.html 'Size: ' pub trait MyTrait {} + +// @has type_layout/enum.Variants.html 'Size: ' +// @has - '2 bytes' +// @has - 'A: 0 bytes' +// @has - 'B: 1 byte' +pub enum Variants { + A, + B(u8), +} + +// @has type_layout/enum.WithNiche.html 'Size: ' +// @has - //p '4 bytes' +// @has - 'None: 0 bytes' +// @has - 'Some: 4 bytes' +pub enum WithNiche { + None, + Some(std::num::NonZeroU32), +}