|
|
|
|
<!DOCTYPE HTML>
|
|
|
|
|
<html lang="zh-CN" class="light" dir="ltr">
|
|
|
|
|
<head>
|
|
|
|
|
<!-- Book generated using mdBook -->
|
|
|
|
|
<meta charset="UTF-8">
|
|
|
|
|
<title>数据布局 - Rust语言圣经(Rust Course)</title>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom HTML head -->
|
|
|
|
|
|
|
|
|
|
<meta name="description" content="">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
|
|
|
<meta name="theme-color" content="#ffffff">
|
|
|
|
|
|
|
|
|
|
<link rel="icon" href="../../favicon.svg">
|
|
|
|
|
<link rel="shortcut icon" href="../../favicon.png">
|
|
|
|
|
<link rel="stylesheet" href="../../css/variables.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/general.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/chrome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../css/print.css" media="print">
|
|
|
|
|
|
|
|
|
|
<!-- Fonts -->
|
|
|
|
|
<link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
|
|
|
|
|
<link rel="stylesheet" href="../../fonts/fonts.css">
|
|
|
|
|
|
|
|
|
|
<!-- Highlight.js Stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../highlight.css">
|
|
|
|
|
<link rel="stylesheet" href="../../tomorrow-night.css">
|
|
|
|
|
<link rel="stylesheet" href="../../ayu-highlight.css">
|
|
|
|
|
|
|
|
|
|
<!-- Custom theme stylesheets -->
|
|
|
|
|
<link rel="stylesheet" href="../../theme/style.css">
|
|
|
|
|
|
|
|
|
|
</head>
|
|
|
|
|
<body class="sidebar-visible no-js">
|
|
|
|
|
<div id="body-container">
|
|
|
|
|
<!-- Provide site root to javascript -->
|
|
|
|
|
<script>
|
|
|
|
|
var path_to_root = "../../";
|
|
|
|
|
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
|
|
|
|
<script>
|
|
|
|
|
try {
|
|
|
|
|
var theme = localStorage.getItem('mdbook-theme');
|
|
|
|
|
var sidebar = localStorage.getItem('mdbook-sidebar');
|
|
|
|
|
|
|
|
|
|
if (theme.startsWith('"') && theme.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
|
|
|
|
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
|
|
|
|
}
|
|
|
|
|
} catch (e) { }
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- Set the theme before any content is loaded, prevents flash -->
|
|
|
|
|
<script>
|
|
|
|
|
var theme;
|
|
|
|
|
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
|
|
|
|
if (theme === null || theme === undefined) { theme = default_theme; }
|
|
|
|
|
var html = document.querySelector('html');
|
|
|
|
|
html.classList.remove('light')
|
|
|
|
|
html.classList.add(theme);
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
body.classList.remove('no-js')
|
|
|
|
|
body.classList.add('js');
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
|
|
|
|
|
|
|
|
|
|
<!-- Hide / unhide sidebar before it is displayed -->
|
|
|
|
|
<script>
|
|
|
|
|
var body = document.querySelector('body');
|
|
|
|
|
var sidebar = null;
|
|
|
|
|
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
|
|
|
|
|
if (document.body.clientWidth >= 1080) {
|
|
|
|
|
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
|
|
|
|
sidebar = sidebar || 'visible';
|
|
|
|
|
} else {
|
|
|
|
|
sidebar = 'hidden';
|
|
|
|
|
}
|
|
|
|
|
sidebar_toggle.checked = sidebar === 'visible';
|
|
|
|
|
body.classList.remove('sidebar-visible');
|
|
|
|
|
body.classList.add("sidebar-" + sidebar);
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
|
|
|
|
<div class="sidebar-scrollbox">
|
|
|
|
|
<ol class="chapter"><li class="chapter-item affix "><a href="../../about-book.html">关于本书</a></li><li class="chapter-item affix "><a href="../../into-rust.html">进入 Rust 编程世界</a></li><li class="chapter-item affix "><a href="../../first-try/sth-you-should-not-do.html">避免从入门到放弃</a></li><li class="chapter-item affix "><a href="../../community.html">社区和锈书</a></li><li class="spacer"></li><li class="chapter-item affix "><a href="../../some-thoughts.html">Xobserve: 一切皆可观测</a></li><li class="chapter-item affix "><a href="../../beat-ai.html">BeatAI: 工程师 AI 入门圣经</a></li><li class="chapter-item affix "><li class="part-title">Rust 语言基础学习</li><li class="spacer"></li><li class="chapter-item "><a href="../../first-try/intro.html"><strong aria-hidden="true">1.</strong> 寻找牛刀,以便小试</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../first-try/installation.html"><strong aria-hidden="true">1.1.</strong> 安装 Rust 环境</a></li><li class="chapter-item "><a href="../../first-try/editor.html"><strong aria-hidden="true">1.2.</strong> 墙推 VSCode!</a></li><li class="chapter-item "><a href="../../first-try/cargo.html"><strong aria-hidden="true">1.3.</strong> 认识 Cargo</a></li><li class="chapter-item "><a href="../../first-try/hello-world.html"><strong aria-hidden="true">1.4.</strong> 不仅仅是 Hello world</a></li><li class="chapter-item "><a href="../../first-try/slowly-downloading.html"><strong aria-hidden="true">1.5.</strong> 下载依赖太慢了?</a></li></ol></li><li class="chapter-item "><a href="../../basic/intro.html"><strong aria-hidden="true">2.</strong> Rust 基础入门</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/variable.html"><strong aria-hidden="true">2.1.</strong> 变量绑定与解构</a></li><li class="chapter-item "><a href="../../basic/base-type/index.html"><strong aria-hidden="true">2.2.</strong> 基本类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/base-type/numbers.html"><strong aria-hidden="true">2.2.1.</strong> 数值类型</a></li><li class="chapter-item "><a href="../../basic/base-type/char-bool.html"><strong aria-hidden="true">2.2.2.</strong> 字符、布尔、单元类型</a></li><li class="chapter-item "><a href="../../basic/base-type/statement-expression.html"><strong aria-hidden="true">2.2.3.</strong> 语句与表达式</a></li><li class="chapter-item "><a href="../../basic/base-type/function.html"><strong aria-hidden="true">2.2.4.</strong> 函数</a></li></ol></li><li class="chapter-item "><a href="../../basic/ownership/index.html"><strong aria-hidden="true">2.3.</strong> 所有权和借用</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/ownership/ownership.html"><strong aria-hidden="true">2.3.1.</strong> 所有权</a></li><li class="chapter-item "><a href="../../basic/ownership/borrowing.html"><strong aria-hidden="true">2.3.2.</strong> 引用与借用</a></li></ol></li><li class="chapter-item "><a href="../../basic/compound-type/intro.html"><strong aria-hidden="true">2.4.</strong> 复合类型</a><a class="toggle"><div>❱</div></a></li><li><ol class="section"><li class="chapter-item "><a href="../../basic/compound-type/string-slice.html"><strong aria-hidden="true">2.4.1.</strong> 字符串与切片</a></li><li class="chapter-item "><a href="../../basic/compound-type/tuple.html"><strong aria-hidden="true">2.4.2.</strong> 元组</a></li><li class="chapter-item "><a href="../../basic/compound-type/struct.html"><strong aria-hidden="true">2.4.3.</strong> 结构体</a></li><li class="chapter-item "><a href="../../basic/compound-type/enum.html"><strong aria-hidden="true">2.4.4.</strong> 枚举</a></li><li class="chapter-item "><a href="../../basic/compound-type/array.html"><strong aria-hidden="true">2.4.5.</strong> 数组</a></l
|
|
|
|
|
</div>
|
|
|
|
|
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
|
|
|
|
|
<div class="sidebar-resize-indicator"></div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
<!-- Track and set sidebar scroll position -->
|
|
|
|
|
<script>
|
|
|
|
|
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
|
|
|
|
|
sidebarScrollbox.addEventListener('click', function(e) {
|
|
|
|
|
if (e.target.tagName === 'A') {
|
|
|
|
|
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
|
|
|
|
|
}
|
|
|
|
|
}, { passive: true });
|
|
|
|
|
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
|
|
|
|
|
sessionStorage.removeItem('sidebar-scroll');
|
|
|
|
|
if (sidebarScrollTop) {
|
|
|
|
|
// preserve sidebar scroll position when navigating via links within sidebar
|
|
|
|
|
sidebarScrollbox.scrollTop = sidebarScrollTop;
|
|
|
|
|
} else {
|
|
|
|
|
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
|
|
|
|
|
var activeSection = document.querySelector('#sidebar .active');
|
|
|
|
|
if (activeSection) {
|
|
|
|
|
activeSection.scrollIntoView({ block: 'center' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="page-wrapper" class="page-wrapper">
|
|
|
|
|
|
|
|
|
|
<div class="page">
|
|
|
|
|
<div id="menu-bar-hover-placeholder"></div>
|
|
|
|
|
<div id="menu-bar" class="menu-bar sticky">
|
|
|
|
|
<div class="left-buttons">
|
|
|
|
|
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
|
|
|
|
<i class="fa fa-bars"></i>
|
|
|
|
|
</label>
|
|
|
|
|
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
|
|
|
|
<i class="fa fa-paint-brush"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
|
|
|
|
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
|
|
|
|
</ul>
|
|
|
|
|
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
|
|
|
|
<i class="fa fa-search"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<h1 class="menu-title">Rust语言圣经(Rust Course)</h1>
|
|
|
|
|
|
|
|
|
|
<div class="right-buttons">
|
|
|
|
|
<a href="../../print.html" title="Print this book" aria-label="Print this book">
|
|
|
|
|
<i id="print-button" class="fa fa-print"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course" title="Git repository" aria-label="Git repository">
|
|
|
|
|
<i id="git-repository-button" class="fa fa-github"></i>
|
|
|
|
|
</a>
|
|
|
|
|
<a href="https://github.com/sunface/rust-course/edit/main/src/too-many-lists/bad-stack/layout.md" title="Suggest an edit" aria-label="Suggest an edit">
|
|
|
|
|
<i id="git-edit-button" class="fa fa-edit"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<div id="search-wrapper" class="hidden">
|
|
|
|
|
<form id="searchbar-outer" class="searchbar-outer">
|
|
|
|
|
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
|
|
|
|
</form>
|
|
|
|
|
<div id="searchresults-outer" class="searchresults-outer hidden">
|
|
|
|
|
<div id="searchresults-header" class="searchresults-header"></div>
|
|
|
|
|
<ul id="searchresults">
|
|
|
|
|
</ul>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
|
|
|
|
<script>
|
|
|
|
|
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
|
|
|
|
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
|
|
|
|
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
|
|
|
|
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
|
|
|
|
});
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<div id="content" class="content">
|
|
|
|
|
<!-- Page table of contents -->
|
|
|
|
|
<div class="sidetoc"><nav class="pagetoc"></nav></div>
|
|
|
|
|
<main>
|
|
|
|
|
<h1 id="基本数据布局-layout-"><a class="header" href="#基本数据布局-layout-">基本数据布局( Layout )</a></h1>
|
|
|
|
|
<p>发现一件尴尬的事情,之前介绍了这么多,但是竟然没有介绍链表是什么...亡羊补牢未为晚也,链表就是一系列存储在堆上的连续数据,大家是不是发现这个定义跟动态数据 <code>Vector</code> 非常相似,那么区别在于什么呢?</p>
|
|
|
|
|
<p>区别就在于链表中的每一个元素都指向下一个元素,最终形成 - 顾名思义的链表: <code>A1 -> A2 -> A3 -> Null</code>。 而数组中的元素只是连续排列,并不存在前一个元素指向后一个元素的情况,而是每个元素通过下标索引来访问。</p>
|
|
|
|
|
<p>既然函数式语言的程序员最常使用链表,那么我们来看看他们给出的定义长什么样:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>List a = Empty | Elem a (List a)
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>mu...看上去非常像一个数学定义,我们可以这样阅读它, 列表 a 要么是空,要么是一个元素后面再跟着一个列表。非常递归也不咋好懂的定义,果然,这很函数式语言。</p>
|
|
|
|
|
<p>下面我们再来使用 Rust 的方式对链表进行下定义,为了简单性,这先不使用泛型:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>// in first.rs
|
|
|
|
|
|
|
|
|
|
pub enum List {
|
|
|
|
|
Empty,
|
|
|
|
|
Elem(i32, List),
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>喔,看上去人模狗样,来,运行下看看:</p>
|
|
|
|
|
<pre><code class="language-shell">$ cargo run
|
|
|
|
|
error[E0072]: recursive type `List` has infinite size
|
|
|
|
|
--> src/first.rs:1:1
|
|
|
|
|
|
|
|
|
|
|
1 | pub enum List {
|
|
|
|
|
| ^^^^^^^^^^^^^ recursive type has infinite size
|
|
|
|
|
2 | Empty,
|
|
|
|
|
3 | Elem(i32, List),
|
|
|
|
|
| ---- recursive without indirection
|
|
|
|
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable
|
|
|
|
|
|
|
|
|
|
|
3 | Elem(i32, Box<List>),
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>帅不过 3 秒的玩意儿~~ 好在这个问题,我们在<a href="https://course.rs/advance/smart-pointer/box.html#%E5%B0%86%E5%8A%A8%E6%80%81%E5%A4%A7%E5%B0%8F%E7%B1%BB%E5%9E%8B%E5%8F%98%E4%B8%BA-sized-%E5%9B%BA%E5%AE%9A%E5%A4%A7%E5%B0%8F%E7%B1%BB%E5%9E%8B">之前的章节</a>中就讲过了,简而言之,当前的类型是<a href="https://course.rs/advance/into-types/sized.html">不定长</a>的,对于 Rust 编译器而言,所有栈上的类型都必须在编译期有固定的长度,一个简单的解决方案就是使用 <code>Box</code> 将值封装到堆上,然后使用栈上的定长指针来指向堆上不定长的值。</p>
|
|
|
|
|
<p>实际上,如果大家有仔细看编译错误的话,它还给出了我们提示: <code>Elem(i32, Box<List>)</code>,和我们之前的结论一致,下面来试试:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub enum List {
|
|
|
|
|
Empty,
|
|
|
|
|
Elem(i32, Box<List>),
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<pre><code class="language-shell">$ cargo build
|
|
|
|
|
|
|
|
|
|
Finished dev [unoptimized + debuginfo] target(s) in 0.22s
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>万能的编译器再一次拯救了我们,这次的代码成功完成了编译。但是这依然是不咋滴的 <code>List</code> 定义,有几个原因。</p>
|
|
|
|
|
<p>首先,考虑一个拥有两个元素的 <code>List</code>:</p>
|
|
|
|
|
<pre><code class="language-shell">[] = Stack
|
|
|
|
|
() = Heap
|
|
|
|
|
|
|
|
|
|
[Elem A, ptr] -> (Elem B, ptr) -> (Empty, *junk*)
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>这里有两个问题:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li>最后一个节点分配在了堆上,但是它看上去根本不像一个 <code>Node</code></li>
|
|
|
|
|
<li>第一个 <code>Node</code> 是存储在栈上的,结果一家子不能整整齐齐的待在堆上了</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>这两点看上去好像有点矛盾:你希望所有节点在堆上,但是又觉得最后一个节点不应该在堆上。那再来考虑另一种布局( Layout )方式:</p>
|
|
|
|
|
<pre><code class="language-shell">[ptr] -> (Elem A, ptr) -> (Elem B, *null*)
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>在这种布局下,我们无条件的在堆上创建所有节点,最大的区别就是这里不再有 <code>junk</code>。那么什么是 <code>junk</code>?为了理解这个概念,先来看看枚举类型的内存布局( Layout )长什么样:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>enum Foo {
|
|
|
|
|
D1(u8),
|
|
|
|
|
D2(u16),
|
|
|
|
|
D3(u32),
|
|
|
|
|
D4(u64)
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>大家觉得 <code>Foo::D1(99)</code> 占用多少内存空间?是 <code>u8</code> 对应的 1 个字节吗?答案是 8 个字节( 为了好理解,这里不考虑 enum tag 所占用的额外空间 ),因为枚举有一个特点,枚举成员占用的内存空间大小跟最大的成员对齐,在这个例子中,所有的成员都会跟 <code>u64</code> 进行对齐。</p>
|
|
|
|
|
<p>在理解了这点后,再回到我们的 <code>List</code> 定义。这里最大的问题就是尽管 <code>List::Empty</code> 是空的节点,但是它依然得消耗和其它节点一样的内存空间。</p>
|
|
|
|
|
<p>与其让一个节点不进行内存分配,不如让它一直进行内存分配,无论是否有内容,因为后者会保证节点内存布局的一致性。这种一致性对于 <code>push</code> 和 <code>pop</code> 节点来说可能没有什么影响,但是对于链表的分割和合并而言,就有意义了。</p>
|
|
|
|
|
<p>下面,我们对之前两种不同布局的 List 进行下分割:</p>
|
|
|
|
|
<pre><code class="language-shell">layout 1:
|
|
|
|
|
|
|
|
|
|
[Elem A, ptr] -> (Elem B, ptr) -> (Elem C, ptr) -> (Empty *junk*)
|
|
|
|
|
|
|
|
|
|
split off C:
|
|
|
|
|
|
|
|
|
|
[Elem A, ptr] -> (Elem B, ptr) -> (Empty *junk*)
|
|
|
|
|
[Elem C, ptr] -> (Empty *junk*)
|
|
|
|
|
</code></pre>
|
|
|
|
|
<pre><code class="language-shell">layout 2:
|
|
|
|
|
|
|
|
|
|
[ptr] -> (Elem A, ptr) -> (Elem B, ptr) -> (Elem C, *null*)
|
|
|
|
|
|
|
|
|
|
split off C:
|
|
|
|
|
|
|
|
|
|
[ptr] -> (Elem A, ptr) -> (Elem B, *null*)
|
|
|
|
|
[ptr] -> (Elem C, *null*)
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>可以看出,在布局 1 中,需要将 <code>C</code> 节点从堆上拷贝到栈中,而布局 2 则无需此过程。而且从分割后的布局清晰度而言,2 也要优于 1。</p>
|
|
|
|
|
<p>现在,我们应该都相信布局 1 更糟糕了,而且不幸的是,我们之前的实现就是布局 1, 那么该如何实现新的布局呢 ?也许,我们可以实现类似如下的 <code>List</code> :</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub enum List {
|
|
|
|
|
Empty,
|
|
|
|
|
ElemThenEmpty(i32),
|
|
|
|
|
ElemThenNotEmpty(i32, Box<List>),
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>但是,你们有没有觉得更糟糕了...有些不忍直视的感觉。这让我们的代码复杂度大幅提升,例如你现在得实现一个完全不合法的状态: <code>ElemThenNotEmpty(0, Box(Empty))</code>,而且这种实现依然有之前的不一致性的问题。</p>
|
|
|
|
|
<p>之前我们提到过枚举成员的内存空间占用和 enum tag 问题,实际上我们可以创建一个特例:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>enum Foo {
|
|
|
|
|
A,
|
|
|
|
|
B(ContainsANonNullPtr),
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>在这里 <code>null</code> 指针的优化就开始介入了,它会消除枚举成员 <code>A</code> 占用的额外空间,原因在于编译器可以直接将 <code>A</code> 优化成 <code>0</code>,而 <code>B</code> 则不行,因为它包含了非 <code>null</code> 指针。这样一来,编译器就无需给 <code>A</code> 打 tag 进行识别了,而是直接通过 <code>0</code> 就能识别出这是 <code>A</code> 成员,非 <code>0</code> 的自然就是 <code>B</code> 成员。</p>
|
|
|
|
|
<p>事实上,编译器还会对枚举做一些其他优化,但是 <code>null</code> 指针优化是其中最重要的一条。</p>
|
|
|
|
|
<p>所以我们应该怎么避免多余的 <code>junk</code>,保持内存分配的一致性,还能保持 <code>null</code> 指针优化呢?枚举可以让我们声明一个类型用于表达多个不同的值,而结构体可以声明一个类型同时包含多个值,只要将这两个类型结合在一起,就能实现之前的目标: 枚举类型用于表示 <code>List</code>,结构体类型用于表示 <code>Node</code>.</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>struct Node {
|
|
|
|
|
elem: i32,
|
|
|
|
|
next: List,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub enum List {
|
|
|
|
|
Empty,
|
|
|
|
|
More(Box<Node>),
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>让我们看看新的定义是否符合之前的目标:</p>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><code>List</code> 的尾部不会再分配多余的 junk 值,通过!</li>
|
|
|
|
|
<li><code>List</code> 枚举的形式可以享受 <code>null</code> 指针优化,完美!</li>
|
|
|
|
|
<li>所有的元素都拥有统一的内存分配,Good!</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<p>很好,我们准确构建了之前想要的内存布局,并且证明了最初的内存布局问题多多,编译下试试:</p>
|
|
|
|
|
<pre><code class="language-shell">error[E0446]: private type `Node` in public interface
|
|
|
|
|
--> src/first.rs:8:10
|
|
|
|
|
|
|
|
|
|
|
1 | struct Node {
|
|
|
|
|
| ----------- `Node` declared as private
|
|
|
|
|
...
|
|
|
|
|
8 | More(Box<Node>),
|
|
|
|
|
| ^^^^^^^^^ can't leak private type
|
|
|
|
|
</code></pre>
|
|
|
|
|
<p>在英文书中,这里是一个 warning ,但是在笔者使用的最新版中(Rust 1.59),该 warning 已经变成一个错误。主要原因在于 <code>pub enum</code> 会要求它的所有成员必须是 <code>pub</code>,但是由于 <code>Node</code> 没有声明为 <code>pub</code>,因此产生了冲突。</p>
|
|
|
|
|
<p>这里最简单的解决方法就是将 <code>Node</code> 结构体和它的所有字段都标记为 <code>pub</code> :</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub struct Node {
|
|
|
|
|
pub elem: i32,
|
|
|
|
|
pub next: List,
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>但是从编程的角度而言,我们还是希望让实现细节只保留在内部,而不是对外公开,因此以下代码相对会更加适合:</p>
|
|
|
|
|
<pre><pre class="playground"><code class="language-rust edition2021"><span class="boring">#![allow(unused)]
|
|
|
|
|
</span><span class="boring">fn main() {
|
|
|
|
|
</span>pub struct List {
|
|
|
|
|
head: Link,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
enum Link {
|
|
|
|
|
Empty,
|
|
|
|
|
More(Box<Node>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Node {
|
|
|
|
|
elem: i32,
|
|
|
|
|
next: Link,
|
|
|
|
|
}
|
|
|
|
|
<span class="boring">}</span></code></pre></pre>
|
|
|
|
|
<p>从代码层面看,貌似多了一层封装,但是实际上 <code>List</code> 只有一个字段,因此结构体的大小跟字段大小是相等的,没错,传说中的零开销抽象!</p>
|
|
|
|
|
<p>至此,一个令人满意的数据布局就已经设计完成,下面一起来看看该如何使用这些数据。</p>
|
|
|
|
|
|
|
|
|
|
<div id="giscus-container"></div>
|
|
|
|
|
</main>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wrapper" aria-label="Page navigation">
|
|
|
|
|
<!-- Mobile navigation buttons -->
|
|
|
|
|
<a rel="prev" href="../../too-many-lists/bad-stack/intro.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../too-many-lists/bad-stack/basic-operations.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<div style="clear: both"></div>
|
|
|
|
|
</nav>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
|
|
|
|
<a rel="prev" href="../../too-many-lists/bad-stack/intro.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
|
|
|
|
<i class="fa fa-angle-left"></i>
|
|
|
|
|
</a>
|
|
|
|
|
|
|
|
|
|
<a rel="next prefetch" href="../../too-many-lists/bad-stack/basic-operations.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
|
|
|
|
<i class="fa fa-angle-right"></i>
|
|
|
|
|
</a>
|
|
|
|
|
</nav>
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<script>
|
|
|
|
|
window.playground_copyable = true;
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<script src="../../ace.js"></script>
|
|
|
|
|
<script src="../../editor.js"></script>
|
|
|
|
|
<script src="../../mode-rust.js"></script>
|
|
|
|
|
<script src="../../theme-dawn.js"></script>
|
|
|
|
|
<script src="../../theme-tomorrow_night.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../elasticlunr.min.js"></script>
|
|
|
|
|
<script src="../../mark.min.js"></script>
|
|
|
|
|
<script src="../../searcher.js"></script>
|
|
|
|
|
|
|
|
|
|
<script src="../../clipboard.min.js"></script>
|
|
|
|
|
<script src="../../highlight.js"></script>
|
|
|
|
|
<script src="../../book.js"></script>
|
|
|
|
|
|
|
|
|
|
<script type="text/javascript" charset="utf-8">
|
|
|
|
|
var pagePath = "too-many-lists/bad-stack/layout.md"
|
|
|
|
|
</script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<!-- Custom JS scripts -->
|
|
|
|
|
<script src="../../assets/custom.js"></script>
|
|
|
|
|
<script src="../../assets/bigPicture.js"></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
</body>
|
|
|
|
|
</html>
|