Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > 878cdd00a13d17a73c6619a777ef5d74 > files > 2471

rust-doc-1.19.0-1.mga6.x86_64.rpm

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>How Safe and Unsafe Interact - </title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="meet-safe-and-unsafe.html"><strong>1.</strong> Meet Safe and Unsafe</a></li><li><ul class="section"><li><a href="safe-unsafe-meaning.html" class="active"><strong>1.1.</strong> How Safe and Unsafe Interact</a></li><li><a href="working-with-unsafe.html"><strong>1.2.</strong> Working with Unsafe</a></li></ul></li><li><a href="data.html"><strong>2.</strong> Data Layout</a></li><li><ul class="section"><li><a href="repr-rust.html"><strong>2.1.</strong> repr(Rust)</a></li><li><a href="exotic-sizes.html"><strong>2.2.</strong> Exotically Sized Types</a></li><li><a href="other-reprs.html"><strong>2.3.</strong> Other reprs</a></li></ul></li><li><a href="ownership.html"><strong>3.</strong> Ownership</a></li><li><ul class="section"><li><a href="references.html"><strong>3.1.</strong> References</a></li><li><a href="lifetimes.html"><strong>3.2.</strong> Lifetimes</a></li><li><a href="lifetime-mismatch.html"><strong>3.3.</strong> Limits of Lifetimes</a></li><li><a href="lifetime-elision.html"><strong>3.4.</strong> Lifetime Elision</a></li><li><a href="unbounded-lifetimes.html"><strong>3.5.</strong> Unbounded Lifetimes</a></li><li><a href="hrtb.html"><strong>3.6.</strong> Higher-Rank Trait Bounds</a></li><li><a href="subtyping.html"><strong>3.7.</strong> Subtyping and Variance</a></li><li><a href="dropck.html"><strong>3.8.</strong> Drop Check</a></li><li><a href="phantom-data.html"><strong>3.9.</strong> PhantomData</a></li><li><a href="borrow-splitting.html"><strong>3.10.</strong> Splitting Borrows</a></li></ul></li><li><a href="conversions.html"><strong>4.</strong> Type Conversions</a></li><li><ul class="section"><li><a href="coercions.html"><strong>4.1.</strong> Coercions</a></li><li><a href="dot-operator.html"><strong>4.2.</strong> The Dot Operator</a></li><li><a href="casts.html"><strong>4.3.</strong> Casts</a></li><li><a href="transmutes.html"><strong>4.4.</strong> Transmutes</a></li></ul></li><li><a href="uninitialized.html"><strong>5.</strong> Uninitialized Memory</a></li><li><ul class="section"><li><a href="checked-uninit.html"><strong>5.1.</strong> Checked</a></li><li><a href="drop-flags.html"><strong>5.2.</strong> Drop Flags</a></li><li><a href="unchecked-uninit.html"><strong>5.3.</strong> Unchecked</a></li></ul></li><li><a href="obrm.html"><strong>6.</strong> Ownership Based Resource Management</a></li><li><ul class="section"><li><a href="constructors.html"><strong>6.1.</strong> Constructors</a></li><li><a href="destructors.html"><strong>6.2.</strong> Destructors</a></li><li><a href="leaking.html"><strong>6.3.</strong> Leaking</a></li></ul></li><li><a href="unwinding.html"><strong>7.</strong> Unwinding</a></li><li><ul class="section"><li><a href="exception-safety.html"><strong>7.1.</strong> Exception Safety</a></li><li><a href="poisoning.html"><strong>7.2.</strong> Poisoning</a></li></ul></li><li><a href="concurrency.html"><strong>8.</strong> Concurrency</a></li><li><ul class="section"><li><a href="races.html"><strong>8.1.</strong> Races</a></li><li><a href="send-and-sync.html"><strong>8.2.</strong> Send and Sync</a></li><li><a href="atomics.html"><strong>8.3.</strong> Atomics</a></li></ul></li><li><a href="vec.html"><strong>9.</strong> Implementing Vec</a></li><li><ul class="section"><li><a href="vec-layout.html"><strong>9.1.</strong> Layout</a></li><li><a href="vec-alloc.html"><strong>9.2.</strong> Allocating</a></li><li><a href="vec-push-pop.html"><strong>9.3.</strong> Push and Pop</a></li><li><a href="vec-dealloc.html"><strong>9.4.</strong> Deallocating</a></li><li><a href="vec-deref.html"><strong>9.5.</strong> Deref</a></li><li><a href="vec-insert-remove.html"><strong>9.6.</strong> Insert and Remove</a></li><li><a href="vec-into-iter.html"><strong>9.7.</strong> IntoIter</a></li><li><a href="vec-raw.html"><strong>9.8.</strong> RawVec</a></li><li><a href="vec-drain.html"><strong>9.9.</strong> Drain</a></li><li><a href="vec-zsts.html"><strong>9.10.</strong> Handling Zero-Sized Types</a></li><li><a href="vec-final.html"><strong>9.11.</strong> Final Code</a></li></ul></li><li><a href="arc-and-mutex.html"><strong>10.</strong> Implementing Arc and Mutex</a></li><li><a href="ffi.html"><strong>11.</strong> FFI</a></li></ul>
        </div>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

                    <h1 class="menu-title"></h1>

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>

                <div id="content" class="content">
                    <a class="header" href="safe-unsafe-meaning.html#how-safe-and-unsafe-interact" id="how-safe-and-unsafe-interact"><h1>How Safe and Unsafe Interact</h1></a>
<p>What's the relationship between Safe Rust and Unsafe Rust? How do they
interact?</p>
<p>The separation between Safe Rust and Unsafe Rust is controlled with the
<code>unsafe</code> keyword, which acts as an interface from one to the other. This is
why we can say Safe Rust is a safe language: all the unsafe parts are kept
exclusively behind the boundary.</p>
<p>The <code>unsafe</code> keyword has two uses: to declare the existence of contracts the
compiler can't check, and to declare that the adherence of some code to
those contracts has been checked by the programmer.</p>
<p>You can use <code>unsafe</code> to indicate the existence of unchecked contracts on
<em>functions</em> and on <em>trait declarations</em>. On functions, <code>unsafe</code> means that
users of the function must check that function's documentation to ensure
they are using it in a way that maintains the contracts the function
requires. On trait declarations, <code>unsafe</code> means that implementors of the
trait must check the trait documentation to ensure their implementation
maintains the contracts the trait requires.</p>
<p>You can use <code>unsafe</code> on a block to declare that all constraints required
by an unsafe function within the block have been adhered to, and the code
can therefore be trusted. You can use <code>unsafe</code> on a trait implementation
to declare that the implementation of that trait has adhered to whatever
contracts the trait's documentation requires.</p>
<p>The standard library has a number of unsafe functions, including:</p>
<ul>
<li><code>slice::get_unchecked</code>, which performs unchecked indexing, allowing
memory safety to be freely violated.</li>
<li><code>mem::transmute</code> reinterprets some value as having a given type, bypassing
type safety in arbitrary ways (see <a href="conversions.html">conversions</a> for details).</li>
<li>Every raw pointer to a sized type has an intrinstic <code>offset</code> method that
invokes Undefined Behavior if the passed offset is not &quot;in bounds&quot; as
defined by LLVM.</li>
<li>All FFI functions are <code>unsafe</code> because the other language can do arbitrary
operations that the Rust compiler can't check.</li>
</ul>
<p>As of Rust 1.0 there are exactly two unsafe traits:</p>
<ul>
<li><code>Send</code> is a marker trait (a trait with no API) that promises implementors are
safe to send (move) to another thread.</li>
<li><code>Sync</code> is a marker trait that promises threads can safely share implementors
through a shared reference.</li>
</ul>
<p>Much of the Rust standard library also uses Unsafe Rust internally, although
these implementations are rigorously manually checked, and the Safe Rust
interfaces provided on top of these implementations can be assumed to be safe.</p>
<p>The need for all of this separation boils down a single fundamental property
of Safe Rust:</p>
<p><strong>No matter what, Safe Rust can't cause Undefined Behavior.</strong></p>
<p>The design of the safe/unsafe split means that Safe Rust inherently has to
trust that any Unsafe Rust it touches has been written correctly (meaning
the Unsafe Rust actually maintains whatever contracts it is supposed to
maintain). On the other hand, Unsafe Rust has to be very careful about
trusting Safe Rust.</p>
<p>As an example, Rust has the <code>PartialOrd</code> and <code>Ord</code> traits to differentiate
between types which can &quot;just&quot; be compared, and those that provide a total
ordering (where every value of the type is either equal to, greater than,
or less than any other value of the same type). The sorted map type
<code>BTreeMap</code> doesn't make sense for partially-ordered types, and so it
requires that any key type for it implements the <code>Ord</code> trait. However,
<code>BTreeMap</code> has Unsafe Rust code inside of its implementation, and this
Unsafe Rust code cannot assume that any <code>Ord</code> implementation it gets makes
sense. The unsafe portions of <code>BTreeMap</code>'s internals have to be careful to
maintain all necessary contracts, even if a key type's <code>Ord</code> implementation
does not implement a total ordering.</p>
<p>Unsafe Rust cannot automatically trust Safe Rust. When writing Unsafe Rust,
you must be careful to only rely on specific Safe Rust code, and not make
assumptions about potential future Safe Rust code providing the same
guarantees.</p>
<p>This is the problem that <code>unsafe</code> traits exist to resolve. The <code>BTreeMap</code>
type could theoretically require that keys implement a new trait called
<code>UnsafeOrd</code>, rather than <code>Ord</code>, that might look like this:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::cmp::Ordering;

unsafe trait UnsafeOrd {
    fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering;
}

#}</code></pre></pre>
<p>Then, a type would use <code>unsafe</code> to implement <code>UnsafeOrd</code>, indicating that
they've ensured their implementation maintains whatever contracts the
trait expects. In this situation, the Unsafe Rust in the internals of
<code>BTreeMap</code> could trust that the key type's <code>UnsafeOrd</code> implementation is
correct. If it isn't, it's the fault of the unsafe trait implementation
code, which is consistent with Rust's safety guarantees.</p>
<p>The decision of whether to mark a trait <code>unsafe</code> is an API design choice.
Rust has traditionally avoided marking traits unsafe because it makes Unsafe
Rust pervasive, which is not desirable. <code>Send</code> and <code>Sync</code> are marked unsafe
because thread safety is a <em>fundamental property</em> that unsafe code can't
possibly hope to defend against in the way it could defend against a bad
<code>Ord</code> implementation. The decision of whether to mark your own traits <code>unsafe</code>
depends on the same sort of consideration. If <code>unsafe</code> code cannot reasonably
expect to defend against a bad implementation of the trait, then marking the
trait <code>unsafe</code> is a reasonable choice.</p>
<p>As an aside, while <code>Send</code> and <code>Sync</code> are <code>unsafe</code> traits, they are
automatically implemented for types when such derivations are provably safe
to do. <code>Send</code> is automatically derived for all types composed only of values
whose types also implement <code>Send</code>. <code>Sync</code> is automatically derived for all
types composed only of values whose types also implement <code>Sync</code>.</p>
<p>This is the dance of Safe Rust and Unsafe Rust. It is designed to make using
Safe Rust as ergonomic as possible, but requires extra effort and care when
writing Unsafe Rust. The rest of the book is largely a discussion of the sort
of care that must be taken, and what contracts it is expected of Unsafe Rust
to uphold.</p>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="meet-safe-and-unsafe.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="working-with-unsafe.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="meet-safe-and-unsafe.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="working-with-unsafe.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

        <script src="highlight.js"></script>
        <script src="book.js"></script>
    </body>
</html>