Programming Rust: Fast, Safe Systems Development. 2 Ed

Programming Rust: Fast, Safe Systems Development. 2 Ed

Programming Rust: Fast, Safe Systems Development. 2 Ed
Автор: Blandy Jim, Orendorff Jason, Tindall Leonora F. S.
Дата выхода: 2021
Издательство: O’Reilly Media, Inc.
Количество страниц: 1157
Размер файла: 11.7 MB
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы

Preface....5

Who Should Read This Book....6

Why We Wrote This Book....7

Navigating This Book....7

Conventions Used in This Book....8

Using Code Examples....9

O’Reilly Online Learning....10

How to Contact Us....10

Acknowledgments....11

1. Systems Programmers Can Have Nice Things....13

Rust Shoulders the Load for You....15

Parallel Programming Is Tamed....16

And Yet Rust Is Still Fast....17

Rust Makes Collaboration Easier....18

2. A Tour of Rust....20

rustup and Cargo....21

Rust Functions....25

Writing and Running Unit Tests....27

Handling Command-Line Arguments....28

Serving Pages to the Web....35

Concurrency....43

What the Mandelbrot Set Actually Is....45

Parsing Pair Command-Line Arguments....51

Mapping from Pixels to Complex Numbers....55

Plotting the Set....57

Writing Image Files....58

A Concurrent Mandelbrot Program....61

Running the Mandelbrot Plotter....68

Safety Is Invisible....69

Filesystems and Command-Line Tools....70

The Command-Line Interface....72

Reading and Writing Files....75

Find and Replace....76

3. Fundamental Types....80

Fixed-Width Numeric Types....85

Integer Types....85

Checked, Wrapping, Saturating, and Overflowing Arithmetic....91

Floating-Point Types....94

The bool Type....97

Characters....98

Tuples....101

Pointer Types....104

References....105

Boxes....106

Raw Pointers....106

Arrays, Vectors, and Slices....107

Arrays....108

Vectors....110

Slices....114

String Types....116

String Literals....116

Byte Strings....118

Strings in Memory....119

String....121

Using Strings....123

Other String-Like Types....124

Type Aliases....124

Beyond the Basics....125

4. Ownership and Moves....126

Ownership....129

Moves....136

More Operations That Move....144

Moves and Control Flow....146

Moves and Indexed Content....147

Copy Types: The Exception to Moves....150

Rc and Arc: Shared Ownership....155

5. References....160

References to Values....161

Working with References....166

Rust References Versus C++ References....166

Assigning References....168

References to References....169

Comparing References....170

References Are Never Null....171

Borrowing References to Arbitrary Expressions....171

References to Slices and Trait Objects....172

Reference Safety....173

Borrowing a Local Variable....174

Receiving References as Function Arguments....179

Passing References to Functions....182

Returning References....183

Structs Containing References....185

Distinct Lifetime Parameters....189

Omitting Lifetime Parameters....191

Sharing Versus Mutation....193

Taking Arms Against a Sea of Objects....205

6. Expressions....208

An Expression Language....208

Precedence and Associativity....210

Blocks and Semicolons....213

Declarations....215

if and match....218

if let....221

Loops....222

Control Flow in Loops....224

return Expressions....226

Why Rust Has loop....227

Function and Method Calls....230

Fields and Elements....232

Reference Operators....234

Arithmetic, Bitwise, Comparison, and Logical Operators....235

Assignment....236

Type Casts....237

Closures....239

Onward....240

7. Error Handling....241

Panic....241

Unwinding....242

Aborting....244

Result....245

Catching Errors....246

Result Type Aliases....249

Printing Errors....250

Propagating Errors....252

Working with Multiple Error Types....254

Dealing with Errors That “Can’t Happen”....257

Ignoring Errors....259

Handling Errors in main()....260

Declaring a Custom Error Type....262

Why Results?....263

8. Crates and Modules....266

Crates....267

Editions....271

Build Profiles....273

Modules....274

Nested Modules....276

Modules in Separate Files....277

Paths and Imports....280

The Standard Prelude....285

Making use Declarations pub....286

Making Struct Fields pub....286

Statics and Constants....287

Turning a Program into a Library....288

The src/bin Directory....290

Attributes....292

Tests and Documentation....296

Integration Tests....300

Documentation....301

Doc-Tests....305

Specifying Dependencies....309

Versions....310

Cargo.lock....312

Publishing Crates to crates.io....313

Workspaces....316

More Nice Things....318

9. Structs....319

Named-Field Structs....319

Tuple-Like Structs....323

Unit-Like Structs....325

Struct Layout....325

Defining Methods with impl....327

Passing Self as a Box, Rc, or Arc....330

Type-Associated Functions....333

Associated Consts....335

Generic Structs....336

Structs with Lifetime Parameters....340

Deriving Common Traits for Struct Types....341

Interior Mutability....343

10. Enums and Patterns....349

Enums....350

Enums with Data....354

Enums in Memory....355

Rich Data Structures Using Enums....356

Generic Enums....359

Patterns....363

Literals, Variables, and Wildcards in Patterns....368

Tuple and Struct Patterns....369

Array and Slice Patterns....371

Reference Patterns....372

Match Guards....375

Matching Multiple Possibilities....376

Binding with @ Patterns....377

Where Patterns Are Allowed....378

Populating a Binary Tree....380

The Big Picture....382

11. Traits and Generics....384

Using Traits....387

Trait Objects....389

Generic Functions and Type Parameters....392

Which to Use....397

Defining and Implementing Traits....401

Default Methods....402

Traits and Other People’s Types....404

Self in Traits....406

Subtraits....408

Type-Associated Functions....409

Fully Qualified Method Calls....411

Traits That Define Relationships Between Types....414

Associated Types (or How Iterators Work)....415

Generic Traits (or How Operator Overloading Works)....420

impl Trait....421

Associated Consts....424

Reverse-Engineering Bounds....426

Traits as a Foundation....431

12. Operator Overloading....432

Arithmetic and Bitwise Operators....434

Unary Operators....436

Binary Operators....438

Compound Assignment Operators....439

Equivalence Comparisons....441

Ordered Comparisons....446

Index and IndexMut....450

Other Operators....454

13. Utility Traits....456

Drop....458

Sized....463

Clone....467

Copy....469

Deref and DerefMut....470

Default....475

AsRef and AsMut....478

Borrow and BorrowMut....480

From and Into....483

TryFrom and TryInto....488

ToOwned....490

Borrow and ToOwned at Work: The Humble Cow....491

14. Closures....494

Capturing Variables....496

Closures That Borrow....497

Closures That Steal....498

Function and Closure Types....500

Closure Performance....504

Closures and Safety....506

Closures That Kill....506

FnOnce....507

FnMut....510

Copy and Clone for Closures....513

Callbacks....515

Using Closures Effectively....521

15. Iterators....524

The Iterator and IntoIterator Traits....526

Creating Iterators....528

iter and iter_mut Methods....529

IntoIterator Implementations....530

from_fn and successors....533

drain Methods....536

Other Iterator Sources....536

Iterator Adapters....539

map and filter....540

filter_map and flat_map....543

flatten....547

take and take_while....549

skip and skip_while....550

peekable....552

fuse....553

Reversible Iterators and rev....554

inspect....556

chain....557

enumerate....558

zip....559

by_ref....560

cloned, copied....562

cycle....563

Consuming Iterators....564

Simple Accumulation: count, sum, product....564

max, min....565

max_by, min_by....566

max_by_key, min_by_key....567

Comparing Item Sequences....568

any and all....569

position, rposition, and ExactSizeIterator....569

fold and rfold....570

try_fold and try_rfold....572

nth, nth_back....574

last....574

find, rfind, and find_map....575

Building Collections: collect and FromIterator....576

The Extend Trait....579

partition....580

for_each and try_for_each....581

Implementing Your Own Iterators....582

16. Collections....590

Overview....591

Vec....594

Accessing Elements....595

Iteration....598

Growing and Shrinking Vectors....598

Joining....605

Splitting....606

Swapping....611

Sorting and Searching....611

Comparing Slices....614

Random Elements....615

Rust Rules Out Invalidation Errors....616

VecDeque....618

BinaryHeap....621

HashMap and BTreeMap....624

Entries....630

Map Iteration....634

HashSet and BTreeSet....635

Set Iteration....637

When Equal Values Are Different....637

Whole-Set Operations....638

Hashing....641

Using a Custom Hashing Algorithm....643

Beyond the Standard Collections....645

17. Strings and Text....646

Some Unicode Background....647

ASCII, Latin-1, and Unicode....647

UTF-8....648

Text Directionality....650

Characters (char)....651

Classifying Characters....651

Handling Digits....654

Case Conversion for Characters....655

Conversions to and from Integers....657

String and str....657

Creating String Values....659

Simple Inspection....661

Appending and Inserting Text....662

Removing and Replacing Text....665

Conventions for Searching and Iterating....667

Patterns for Searching Text....668

Searching and Replacing....669

Iterating over Text....671

Trimming....675

Case Conversion for Strings....676

Parsing Other Types from Strings....676

Converting Other Types to Strings....677

Borrowing as Other Text-Like Types....679

Accessing Text as UTF-8....680

Producing Text from UTF-8 Data....681

Putting Off Allocation....683

Strings as Generic Collections....686

Formatting Values....687

Formatting Text Values....689

Formatting Numbers....691

Formatting Other Types....694

Formatting Values for Debugging....695

Formatting Pointers for Debugging....697

Referring to Arguments by Index or Name....698

Dynamic Widths and Precisions....699

Formatting Your Own Types....700

Using the Formatting Language in Your Own Code....704

Regular Expressions....706

Basic Regex Use....706

Building Regex Values Lazily....708

Normalization....709

Normalization Forms....711

The unicode-normalization Crate....713

18. Input and Output....715

Readers and Writers....716

Readers....718

Buffered Readers....721

Reading Lines....723

Collecting Lines....727

Writers....728

Files....730

Seeking....731

Other Reader and Writer Types....732

Binary Data, Compression, and Serialization....735

Files and Directories....738

OsStr and Path....738

Path and PathBuf Methods....740

Filesystem Access Functions....745

Reading Directories....747

Platform-Specific Features....749

Networking....751

19. Concurrency....755

Fork-Join Parallelism....757

spawn and join....760

Error Handling Across Threads....763

Sharing Immutable Data Across Threads....765

Rayon....768

Revisiting the Mandelbrot Set....771

Channels....774

Sending Values....776

Receiving Values....782

Running the Pipeline....783

Channel Features and Performance....786

Thread Safety: Send and Sync....789

Piping Almost Any Iterator to a Channel....793

Beyond Pipelines....795

Shared Mutable State....796

What Is a Mutex?....797

Mutex....799

mut and Mutex....802

Why Mutexes Are Not Always a Good Idea....803

Deadlock....805

Poisoned Mutexes....806

Multiconsumer Channels Using Mutexes....806

Read/Write Locks (RwLock)....808

Condition Variables (Condvar)....810

Atomics....811

Global Variables....815

What Hacking Concurrent Code in Rust Is Like....819

20. Asynchronous Programming....820

From Synchronous to Asynchronous....823

Futures....825

Async Functions and Await Expressions....828

Calling Async Functions from Synchronous Code: block_on....832

Spawning Async Tasks....836

Async Blocks....842

Building Async Functions from Async Blocks....845

Spawning Async Tasks on a Thread Pool....847

But Does Your Future Implement Send?....848

Long Running Computations: yield_now and spawn_blocking....852

Comparing Asynchronous Designs....854

A Real Asynchronous HTTP Client....855

An Asynchronous Client and Server....857

Error and Result Types....860

The Protocol....861

Taking User Input: Asynchronous Streams....863

Sending Packets....866

Receiving Packets: More Asynchronous Streams....868

The Client’s Main Function....870

The Server’s Main Function....872

Handling Chat Connections: Async Mutexes....874

The Group Table: Synchronous Mutexes....877

Chat Groups: tokio’s Broadcast Channels....879

Primitive Futures and Executors: When Is a Future Worth Polling Again?....884

Invoking Wakers: spawn_blocking....887

Implementing block_on....890

Pinning....892

The Two Life Stages of a Future....892

Pinned Pointers....898

The Unpin Trait....901

When Is Asynchronous Code Helpful?....902

21. Macros....907

Macro Basics....909

Basics of Macro Expansion....911

Unintended Consequences....913

Repetition....916

Built-In Macros....919

Debugging Macros....923

Building the json! Macro....924

Fragment Types....926

Recursion in Macros....931

Using Traits with Macros....932

Scoping and Hygiene....935

Importing and Exporting Macros....939

Avoiding Syntax Errors During Matching....942

Beyond macro_rules!....943

22. Unsafe Code....946

Unsafe from What?....947

Unsafe Blocks....950

Example: An Efficient ASCII String Type....952

Unsafe Functions....955

Unsafe Block or Unsafe Function?....959

Undefined Behavior....959

Unsafe Traits....963

Raw Pointers....967

Dereferencing Raw Pointers Safely....971

Example: RefWithFlag....972

Nullable Pointers....976

Type Sizes and Alignments....977

Pointer Arithmetic....978

Moving into and out of Memory....980

Example: GapBuffer....987

Panic Safety in Unsafe Code....996

Reinterpreting Memory with Unions....997

Matching Unions....1001

Borrowing Unions....1001

23. Foreign Functions....1003

Finding Common Data Representations....1004

Declaring Foreign Functions and Variables....1010

Using Functions from Libraries....1013

A Raw Interface to libgit2....1018

A Safe Interface to libgit2....1027

Conclusion....1042

Index....1044

Systems programming provides the foundation for the world's computation. Writing performance-sensitive code requires a programming language that puts programmers in control of how memory, processor time, and other system resources are used. The Rust systems programming language combines that control with a modern type system that catches broad classes of common mistakes, from memory management errors to data races between threads.

With this practical guide, experienced systems programmers will learn how to successfully bridge the gap between performance and safety using Rust. Jim Blandy, Jason Orendorff, and Leonora Tindall demonstrate how Rust's features put programmers in control over memory consumption and processor use by combining predictable performance with memory safety and trustworthy concurrency.

You'll learn:

  • Rust's fundamental data types and the core concepts of ownership and borrowing
  • How to write flexible, efficient code with traits and generics
  • How to write fast, multithreaded code without data races
  • Rust's key power tools: closures, iterators, and asynchronous programming
  • Collections, strings and text, input and output, macros, unsafe code, and foreign function interfaces

Похожее:

Список отзывов:

Нет отзывов к книге.