100% found this document useful (1 vote)
21 views

Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications (2nd ed.) 2nd Edition Shing Lyu - Download the full set of chapters carefully compiled

The document promotes the book 'Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications' by Shing Lyu and Andrew Rzeznik, available for download at ebookmass.com. It includes links to additional recommended books on related topics such as serverless applications, machine learning, and data analytics. The content outlines various chapters covering practical applications and projects using Rust programming.

Uploaded by

lellaarauth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
21 views

Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications (2nd ed.) 2nd Edition Shing Lyu - Download the full set of chapters carefully compiled

The document promotes the book 'Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications' by Shing Lyu and Andrew Rzeznik, available for download at ebookmass.com. It includes links to additional recommended books on related topics such as serverless applications, machine learning, and data analytics. The content outlines various chapters covering practical applications and projects using Rust programming.

Uploaded by

lellaarauth
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Visit ebookmass.

com to download the full version and


explore more ebook or textbook

Practical Rust Projects: Build Serverless, AI,


Machine Learning, Embedded, Game, and Web
Applications (2nd ed.) 2nd Edition Shing Lyu

_____ Click the link below to download _____


https://ebookmass.com/product/practical-rust-projects-build-
serverless-ai-machine-learning-embedded-game-and-web-
applications-2nd-ed-2nd-edition-shing-lyu/

Explore and download more ebook or textbook at ebookmass.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Practical Rust Projects - Second Edition Shing Lyu

https://ebookmass.com/product/practical-rust-projects-second-edition-
shing-lyu/

Serverless Web Applications with AWS Amplify: Build Full-


Stack Serverless Applications Using Amazon Web Services
Akshat Paul
https://ebookmass.com/product/serverless-web-applications-with-aws-
amplify-build-full-stack-serverless-applications-using-amazon-web-
services-akshat-paul/

Beginner's Guide to Streamlit with Python: Build Web-Based


Data and Machine Learning Applications 1st Edition Sujay
Raghavendra
https://ebookmass.com/product/beginners-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-1st-
edition-sujay-raghavendra/

Risk Modeling: Practical Applications of Artificial


Intelligence, Machine Learning, and Deep Learning Terisa
Roberts
https://ebookmass.com/product/risk-modeling-practical-applications-of-
artificial-intelligence-machine-learning-and-deep-learning-terisa-
roberts/
Practical MATLAB Deep Learning: A Projects-Based Approach,
2nd Edition Michael Paluszek

https://ebookmass.com/product/practical-matlab-deep-learning-a-
projects-based-approach-2nd-edition-michael-paluszek/

Practical Machine Learning on Databricks (1st Edition)


Debu Sinha

https://ebookmass.com/product/practical-machine-learning-on-
databricks-1st-edition-debu-sinha/

Machine Learning for Business Analytics: Concepts,


Techniques and Applications with JMP Pro, 2nd Edition
Galit Shmueli
https://ebookmass.com/product/machine-learning-for-business-analytics-
concepts-techniques-and-applications-with-jmp-pro-2nd-edition-galit-
shmueli/

Machine Learning for Healthcare Applications Sachi Nandan


Mohanty

https://ebookmass.com/product/machine-learning-for-healthcare-
applications-sachi-nandan-mohanty/

Enterprise AI in the Cloud: A Practical Guide to Deploying


End-to-End Machine Learning and ChatGPT™ Solutions Rabi
Jay
https://ebookmass.com/product/enterprise-ai-in-the-cloud-a-practical-
guide-to-deploying-end-to-end-machine-learning-and-chatgpt-solutions-
rabi-jay/
Practical Rust
Projects
Build Serverless, AI, Machine Learning,
Embedded, Game, and Web Applications

Second Edition

Shing Lyu
Andrew Rzeznik
Practical Rust Projects
Build Serverless, AI, Machine
Learning, Embedded, Game, and
Web Applications
Second Edition

Shing Lyu
Andrew Rzeznik
Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game,
and Web Applications
Shing Lyu Andrew Rzeznik
Amsterdam, The Netherlands Arlington, MA, USA

ISBN-13 (pbk): 978-1-4842-9330-0 ISBN-13 (electronic): 978-1-4842-9331-7


https://doi.org/10.1007/978-1-4842-9331-7

Copyright © 2023 by Shing Lyu and Andrew Rzeznik


This work is subject to copyright. All rights are reserved by the publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: James Markham
Editorial Assistant: Gryffin Winkler
Copy Editor: April Rondeau
Cover designed by eStudioCalamar
Cover image designed by xb100 on freepik
Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza,
Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, email orders-ny@
springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole
member (owner) is Springer Science+Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is
a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback,
or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub (github.com/apress). For more detailed information, please visit http://www.apress.com/
source-code.
Printed on acid-free paper
Table of Contents
About the Authors���������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi


Introduction����������������������������������������������������������������������������������������������������������� xiii

Chapter 1: Welcome to the World of Rust����������������������������������������������������������������� 1


1.1 Who Is This Book For?������������������������������������������������������������������������������������������������������������� 2
1.2 Who Is This Book Not For?������������������������������������������������������������������������������������������������������ 3
1.3 Criteria for Selecting Libraries������������������������������������������������������������������������������������������������ 3
Pure Rust��������������������������������������������������������������������������������������������������������������������������������� 4
Maturity����������������������������������������������������������������������������������������������������������������������������������� 4
Popularity�������������������������������������������������������������������������������������������������������������������������������� 5
1.4 How to Use This Book������������������������������������������������������������������������������������������������������������� 5
Chapters Overview������������������������������������������������������������������������������������������������������������������ 5
1.5 Source Code���������������������������������������������������������������������������������������������������������������������������� 7
1.6 Topics Not Covered����������������������������������������������������������������������������������������������������������������� 8

Chapter 2: Building a Command-line Program��������������������������������������������������������� 9


2.1 What Are You Building?��������������������������������������������������������������������������������������������������������� 10
2.2 Creating a Binary Project������������������������������������������������������������������������������������������������������ 11
2.3 Reading Command-line Arguments with std::env::args������������������������������������������������ 12
2.4 Handling Complex Arguments with Clap����������������������������������������������������������������������������� 13
2.5 Adding Binary Flags�������������������������������������������������������������������������������������������������������������� 17
2.6 Printing to STDERR���������������������������������������������������������������������������������������������������������������� 18
2.7 Printing with Color���������������������������������������������������������������������������������������������������������������� 19
2.8 Reading the Cat Picture from a File�������������������������������������������������������������������������������������� 21
2.9 Handling Errors��������������������������������������������������������������������������������������������������������������������� 24

iii
Table of Contents

2.10 Piping to Other Commands������������������������������������������������������������������������������������������������� 27


Piping to STDOUT Without Color�������������������������������������������������������������������������������������������� 28
Accepting STDIN�������������������������������������������������������������������������������������������������������������������� 29
2.11 Integration Testing�������������������������������������������������������������������������������������������������������������� 30
2.12 Publishing and Distributing the Program���������������������������������������������������������������������������� 34
Install from Source���������������������������������������������������������������������������������������������������������������� 34
Publish to crates.io���������������������������������������������������������������������������������������������������������������� 35
Building Binaries for Distribution������������������������������������������������������������������������������������������� 36
2.13 Conclusion�������������������������������������������������������������������������������������������������������������������������� 38

Chapter 3: Creating Graphical User Interfaces (GUIs)��������������������������������������������� 39


3.1 What Are You Building?��������������������������������������������������������������������������������������������������������� 40
3.2 Building a Text-based User Interface������������������������������������������������������������������������������������ 41
3.3 Showing a Dialog Box����������������������������������������������������������������������������������������������������������� 43
3.4 Handling Simple Keyboard Inputs����������������������������������������������������������������������������������������� 45
3.5 Adding a Dialog��������������������������������������������������������������������������������������������������������������������� 46
3.6 Multi-step Dialogs����������������������������������������������������������������������������������������������������������������� 47
3.7 Reading User Input���������������������������������������������������������������������������������������������������������������� 50
3.8 Moving to Graphical User Interfaces (GUIs)��������������������������������������������������������������������������� 52
3.9 Creating a Window���������������������������������������������������������������������������������������������������������������� 53
3.10 Displaying an Image������������������������������������������������������������������������������������������������������������ 55
3.11 Using Glade to Design the UI����������������������������������������������������������������������������������������������� 58
3.12 Accepting Inputs and Button Clicks������������������������������������������������������������������������������������ 68
3.13 Reading a gtk::Switch���������������������������������������������������������������������������������������������������� 72
3.14 Alternatives������������������������������������������������������������������������������������������������������������������������� 75
3.15 Conclusion�������������������������������������������������������������������������������������������������������������������������� 77

iv
Table of Contents

Chapter 4: High-Performance Web Frontend Using WebAssembly������������������������� 79


4.1 What Is WebAssembly?��������������������������������������������������������������������������������������������������������� 79
4.2 What Are You Building?��������������������������������������������������������������������������������������������������������� 81
4.3 Hello WebAssembly!������������������������������������������������������������������������������������������������������������� 81
Setting Up the Development Environment����������������������������������������������������������������������������� 82
Creating the Project��������������������������������������������������������������������������������������������������������������� 83
Creating the Frontend������������������������������������������������������������������������������������������������������������ 88
4.4 Resizing an Image with WebAssembly��������������������������������������������������������������������������������� 93
Loading an Image File onto the <canvas>���������������������������������������������������������������������������� 97
Passing the Image to Wasm������������������������������������������������������������������������������������������������ 100
4.5 Writing the Whole Frontend in Rust������������������������������������������������������������������������������������ 106
4.6 A Hello World Example�������������������������������������������������������������������������������������������������������� 107
4.7 A Cat Management Application������������������������������������������������������������������������������������������� 112
CSS Styling�������������������������������������������������������������������������������������������������������������������������� 118
Deleting Files����������������������������������������������������������������������������������������������������������������������� 120
4.8 Wasm Alternatives�������������������������������������������������������������������������������������������������������������� 124
4.9 Conclusion�������������������������������������������������������������������������������������������������������������������������� 126

Chapter 5: REST APIs�������������������������������������������������������������������������������������������� 127


5.1 What Are You Building?������������������������������������������������������������������������������������������������������� 129
5.2 Hello Backend World!���������������������������������������������������������������������������������������������������������� 130
5.3 Serving Static Files������������������������������������������������������������������������������������������������������������� 134
5.4 Converting the Cats List to a REST API�������������������������������������������������������������������������������� 141
5.5 Using a Database���������������������������������������������������������������������������������������������������������������� 146
5.6 Adding Cats with a POST Command����������������������������������������������������������������������������������� 157
5.7 API Testing��������������������������������������������������������������������������������������������������������������������������� 165
5.8 Building the Cat Detail API�������������������������������������������������������������������������������������������������� 169
5.9 Input Validation������������������������������������������������������������������������������������������������������������������� 173

v
Table of Contents

5.10 Error Handling������������������������������������������������������������������������������������������������������������������� 176


Using the actix_web::error Helpers������������������������������������������������������������������������������ 177
Using a Generic Error That Has Implemented the ResponseError Trait���������������������������� 179
Using a Custom-Built Error Type������������������������������������������������������������������������������������������ 179
5.11 Customizing the web::Path Extractor Error�������������������������������������������������������������������� 184
5.12 Logging����������������������������������������������������������������������������������������������������������������������������� 185
5.13 Enabling HTTPS����������������������������������������������������������������������������������������������������������������� 193
5.14 Framework Alternatives���������������������������������������������������������������������������������������������������� 196
5.15 Conclusion������������������������������������������������������������������������������������������������������������������������ 199

Chapter 6: Going Serverless with the Amazon AWS Rust SDK����������������������������� 201
6.1 What Are You Building?������������������������������������������������������������������������������������������������������� 202
6.2 What Is AWS Lambda?�������������������������������������������������������������������������������������������������������� 202
6.3 Registering an AWS Account����������������������������������������������������������������������������������������������� 203
6.4 Hello World in Lambda�������������������������������������������������������������������������������������������������������� 204
6.5 The Full Architecture����������������������������������������������������������������������������������������������������������� 210
6.6 Using the AWS Serverless Application Model (AWS SAM)��������������������������������������������������� 211
6.7 Setting Up AWS SAM CLI Credentials���������������������������������������������������������������������������������� 212
6.8 Creating the Catdex Serverless Project������������������������������������������������������������������������������ 212
6.9 Building the Upload API������������������������������������������������������������������������������������������������������� 219
6.10 Building the /cats API����������������������������������������������������������������������������������������������������� 224
6.11 Uploading the Image Using S3 Pre-signed URL���������������������������������������������������������������� 228
6.12 Adding the Frontend���������������������������������������������������������������������������������������������������������� 235
6.13 A Note on Security������������������������������������������������������������������������������������������������������������ 245
6.14 Next Steps������������������������������������������������������������������������������������������������������������������������� 246
6.15 Conclusion������������������������������������������������������������������������������������������������������������������������ 246

Chapter 7: Building a Game���������������������������������������������������������������������������������� 247


7.1 What Are We Building?�������������������������������������������������������������������������������������������������������� 247
7.2 Bevy and the Entity Component System Pattern���������������������������������������������������������������� 248
7.3 Creating a Bevy Project������������������������������������������������������������������������������������������������������� 252
7.4 See the World Through a Camera��������������������������������������������������������������������������������������� 254

vi
Table of Contents

7.5 Adding the Cats������������������������������������������������������������������������������������������������������������������� 256


7.6 Loading a Spritesheet��������������������������������������������������������������������������������������������������������� 260
7.7 Moving the Cats������������������������������������������������������������������������������������������������������������������ 265
7.8 Creating the Ball����������������������������������������������������������������������������������������������������������������� 269
7.9 Can’t Defy Gravity��������������������������������������������������������������������������������������������������������������� 272
7.10 Making the Ball Bounce���������������������������������������������������������������������������������������������������� 274
7.11 Keeping Score������������������������������������������������������������������������������������������������������������������� 280
7.12 Let There Be Music����������������������������������������������������������������������������������������������������������� 288
7.13 Alternatives����������������������������������������������������������������������������������������������������������������������� 291
7.14 Conclusion������������������������������������������������������������������������������������������������������������������������ 292

Chapter 8: Physical Computing in Rust���������������������������������������������������������������� 293


8.1 What Are You Building?������������������������������������������������������������������������������������������������������� 293
8.2 Physical Computing on Raspberry Pi���������������������������������������������������������������������������������� 294
Getting to Know Your Raspberry Pi�������������������������������������������������������������������������������������� 295
Installing Raspberry Pi OS Using Raspberry Pi Imager������������������������������������������������������� 296
Installing the Rust Toolchain������������������������������������������������������������������������������������������������ 298
Understanding the GPIO Pins����������������������������������������������������������������������������������������������� 299
Building an LED Circuit�������������������������������������������������������������������������������������������������������� 300
Controlling the GPIO Output with Rust��������������������������������������������������������������������������������� 302
Reading Button Clicks��������������������������������������������������������������������������������������������������������� 306
8.3 Cross-Compiling to Raspberry Pi���������������������������������������������������������������������������������������� 312
8.4 How Does the GPIO Code Work?����������������������������������������������������������������������������������������� 314
8.5 Where to Go from Here?������������������������������������������������������������������������������������������������������ 318

Chapter 9: Artificial Intelligence and Machine Learning�������������������������������������� 321


9.1 Types of Machine Learning Models������������������������������������������������������������������������������������� 322
9.2 What Are You Building?������������������������������������������������������������������������������������������������������� 323
9.3 Introducing linfa and rusty-machine����������������������������������������������������������������������������������� 325
9.4 Clustering Cat Breeds with K-means���������������������������������������������������������������������������������� 326
Introduction to the K-means Algorithm������������������������������������������������������������������������������� 326
The Training Data����������������������������������������������������������������������������������������������������������������� 329

vii
Table of Contents

Exporting as a CSV�������������������������������������������������������������������������������������������������������������� 334


Moving the Configuration into a File������������������������������������������������������������������������������������ 337
Setting the Configuration File at Runtime��������������������������������������������������������������������������� 340
Visualizing the Data������������������������������������������������������������������������������������������������������������� 341
Details on Adding More Entries������������������������������������������������������������������������������������������� 344
Setting Up K-means������������������������������������������������������������������������������������������������������������ 346
9.5 Detecting Cats Versus Dogs with a Neural Network����������������������������������������������������������� 355
Introduction to Neural Networks����������������������������������������������������������������������������������������� 355
Preparing the Training Data and Testing Data��������������������������������������������������������������������� 357
Setting Up the Neural Network Model��������������������������������������������������������������������������������� 362
Reading the Training and Testing Data�������������������������������������������������������������������������������� 363
Normalizing the Training Data��������������������������������������������������������������������������������������������� 365
Training and Predicting�������������������������������������������������������������������������������������������������������� 367
Making the Prediction��������������������������������������������������������������������������������������������������������� 370
9.6 Alternatives������������������������������������������������������������������������������������������������������������������������� 372
9.7 Conclusion�������������������������������������������������������������������������������������������������������������������������� 373

Chapter 10: What Else Can You Do with Rust?����������������������������������������������������� 375


10.1 The End Is Just the Beginning������������������������������������������������������������������������������������������� 375
10.2 Server-side Rendered Website������������������������������������������������������������������������������������������ 375
10.3 Web Browser and Crawler������������������������������������������������������������������������������������������������ 376
10.4 Mobile������������������������������������������������������������������������������������������������������������������������������� 378
10.5 Operating Systems and Embedded Devices��������������������������������������������������������������������� 381
10.6 The Cloud�������������������������������������������������������������������������������������������������������������������������� 382
10.7 Blockchains and Cryptocurrencies����������������������������������������������������������������������������������� 383
10.8 Unlimited Possibilities of Rust������������������������������������������������������������������������������������������ 384

Index��������������������������������������������������������������������������������������������������������������������� 385

viii
About the Authors
Shing Lyu is a software engineer who is passionate about
open source software. He’s worked on Rust professionally
at Mozilla on the Firefox (Gecko) and Servo browser engine
project. Currently, he works at Amazon Web Services (AWS)
as a solutions architect. Previously, Shing worked at DAZN,
a sports streaming platform, as a backend developer, with a
focus on AWS and serverless technology. Shing has worked
for other world-famous brands such as Intel. He is also
active in the open source community. Being one of the
founders of the Taiwan Rust community, he loves to share
his enthusiasm for Rust with people.

Andrew Rzeznik is a software development engineer at


AWS Cryptography with interests in distributed systems,
languages, tooling, Internet of Things (IoT), and low-level
programming. His primary working language is Rust, but
he considers himself a polyglot, having worked in C, C++,
Python, Java, C#, and many others. Before AWS Andrew
worked in various software positions, with a primary focus
in factory automation. He developed robust yet accessible
distributed machine control frameworks to bring advanced
software patterns and techniques to manufacturing. He also served as a consultant,
where he debugged manufacturing issues at various firms. Andrew received his PhD
in mathematics from the Massachusetts Institute of Technology (MIT), where he wrote
simulations for ocean mining plumes and tested them aboard a research vessel at sea.

ix
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
About the Technical Reviewer
Satej Kumar Sahu works in the role of senior software data
architect at Boeing. He is passionate about technology,
people, and nature. He believes that through technology
focused on sustainability and conscientious decision making
each of us has the power to make this world a better place.
In his free time, he can be seen reading books, playing
basketball, and having fun with friends and family.

xi
Introduction
Almost every programming language has one or more books about it that provide a
deep dive into fundamental syntax, semantics, and functionality. These books are
amazing as both an introduction and a reference. It’s important to be able to dive deep
and fully immerse yourself in a topic to gain a thorough understanding of it. Whenever
I am starting to learn a new language, I look for this kind of foundational text to start my
journey.
After completing this first stage, however, there is a question of where to move next.
Sometimes you’ve learned a language for a very specific purpose, so you focus all your
energies toward using the language for that task. But breadth of learning is also very
important, and can sometimes be harder to find. The best programmers don’t just
know their own specialty, but also have a broad foundation of knowledge along with
background on adjacent subjects. Learning different applications of a language can open
your mind to new ideas both within that language and outside of it. It’s also really fun to
throw together a new project that does something you’ve never done before.
This book was created to provide some of these projects, which will let you take your
core Rust knowledge and apply it to several different areas. Its goal is to expose you to
new ideas and different ways of thinking, and show, not tell, you how Rust can be used.
One of the big reasons I was drawn to Rust as a programming language was how it
embodies the “general purpose” paradigm. If you ask ten different people why they like
the language, you’ll frequently get ten different answers. Some people like it because it’s
low level; it compiles directly to machine code in the same way as C, with all of the fine
control afforded there. However, some people like it because it’s high level, with a strong
type system and advanced macros for working with abstract constructs. Some people
like Rust because it feels like a safer C++, while others learn it as a more performant
alternative to Python. Some people like Rust for its large selection of available packages,
while others like how powerful the core language feels even when the standard library
has been disabled.

xiii
Introduction

A lot of these different views are because Rust exists in a big ecosystem with wildly
different applications, especially for being such a comparatively young language. On
one end, it’s possible to write tiny bare-metal programs whose compiled size can be
measured in hundreds of bytes (not megabytes, not kilobytes, but bytes). On the other
end, people are currently building operating systems, language compilers, and large
distributed systems in Rust. This book was written to share with you a small set of these
interesting applications, and hopefully show you the benefits (and joy) of writing them
in Rust.
A drawback to the approach taken here is that we can’t go into great depth on any
of the topics. A whole book could be written for each single-chapter project we present
here, diving deep into advanced theory, design, and tradeoffs. We chose to instead
focus only on the core essence of each project, providing you with a scaffold that does
something useful and that you can later extend with your own ideas. As any programmer
knows, frequently the hardest parts of a new project are the initial setup, architecture,
and library choices. We’ve tried to provide these components to you as a solid
foundation for your projects, while also trying to include some interesting examples that
touch on important issues in each of the topics.
We hope that this book lets you see the many faces of the Rust programming
language, where it shines, and in some cases the places where a person like you can
make things better. Many programmers feel that the gap between a novice and an expert
is insurmountable, and that the people who build “real” production applications must
have some unique gifts. Hopefully the examples here will help build your confidence
and show you that anyone can build real, practical projects in Rust with a little guidance
and determination.

Source Code
All code used in this book can be found at g­ ithub.com/apress/practical-rust-­
projects-2e.

xiv
CHAPTER 1

Welcome to the World


of Rust
If you’re reading this book, you’re probably as excited about Rust as we are. Since its
first stable release in 2015, Rust has come a long way in terms of features and stability.
Developers around the world are fascinated by how Rust can combine features that
were once thought of as unavoidable trade-offs: performance with memory safety, and
low-level control with productivity. Despite its infamous steep learning curve, Rust has
gained popularity over the years. It was named the “most loved programming language”
in a StackOverflow survey eight years in a row, from 2016 to 2023. In 2022, it was also
named the “most wanted programming language,” just beating out Python. Many big
companies and organizations like Amazon, Facebook, Google, Microsoft, Dropbox, and
npm use Rust in production. The Android platform supports writing native components
in Rust, and, perhaps most interesting of all, Rust is the first language after C to be added
to the Linux Kernel.
How large is the Rust ecosystem currently? If we take a look at crates.io, the official
Rust crates (libraries) registry, there are over 100,000 crates and over fifty million
downloads a day. There are 55 categories on crates.io,1 ranging from command-line
interfaces and cryptography to databases, games, operating systems, web programming,
and more. What does it feel like to use these libraries? How does Rust’s syntax and design
philosophy affect the design of these crates? How can you get started writing some cool
code with real use cases? This book will try to answer these questions.

1
https://crates.io/categories

1
© Shing Lyu and Andrew Rzeznik 2023
S. Lyu and A. Rzeznik, Practical Rust Projects, https://doi.org/10.1007/978-1-4842-9331-7_1
Chapter 1 Welcome to the World of Rust

1.1 Who Is This Book For?


This book will be useful for

• people who already know basic Rust syntax, but want to learn how to
build applications in Rust;

• people who are considering using Rust to build production-ready


systems and want a tour of some of the options; and
• people who wish to have a quick overview of high-level architecture
and programming interface design in other fields.

You might have learned Rust out of curiosity. After finishing all the tutorials and
beginner books, you might have been left wondering, “What should I do next? What
can I build with Rust?” This book will walk you through a few different applications of
Rust, which will help you move beyond basic language theory and into building real
applications. Rust has a fascinating design and many interesting language features, but
simply knowing how to write basic algorithms and data structures won’t necessarily
prepare you for building useful applications. We’ve tried to find the most production-­
ready but also modern Rust libraries to do the job, so you’ll be able to judge if Rust is
ready for the application you’ve envisioned. If it’s not, you might find opportunities to
contribute back to Rust’s community by improving the existing libraries and frameworks,
or by designing and building new ones.
You might have learned Rust for a specific project, like a CLI tool for work or an open-
source browser engine that happens to use Rust. Once you master Rust for that domain,
it’s beneficial to learn Rust for other domains—say, building a game or a website. This will
open you to new ideas that you can apply to the original domain. For example, by building
a game, you’ll know how game engine designers organize their code to make it decoupled
and easy to maintain, while also being very performant. You may never build a game for
work, but that knowledge might influence the architecture of your next project. As another
example, learning how to cross-compile code to a Raspberry Pi might help you understand
how compiling to WebAssembly works. This book aims to take you through a tour of
various applications of Rust like this. You’ll learn what their application programming
interfaces (APIs)2 look like and how they organize their code and architecture.

2
We use the term “API” in a general sense. This includes the functions, structs, and command-line
tools exposed by each library or framework.

2
Chapter 1 Welcome to the World of Rust

1.2 Who Is This Book Not For?


This book might not be that useful for

• people who want to learn the Rust programming language itself;

• people who want to dive deep into one particular field; or

• people who are looking for the most experimental and cutting-edge
Rust use cases.
This book is not a course on the Rust programming language itself, nor is it trying to
teach Rust’s syntax via examples. We’ll focus on the applications themselves and their
domain knowledge, assuming you already know Rust’s syntax and language features
(though we’ll stop to review more advanced features as they are needed by a project).
There are many excellent books on Rust itself, like The Rust Programming Language by
Steve Klabnik and Carol Nichols. You can also find online books, interactive tutorials,
and videos on the Learn Rust section of the official website.3 Each of the topics in this
book can easily be expanded into a book on its own, so we will try to give you a high-­level
understanding of the topic, but won’t go too deep into any of them. We aim to give you a
broad overview of what is possible with Rust and what the developer experience is like.
Therefore, the examples are simplified so people without a background in that particular
field can still get a taste of the mental models used. Also, we’re not advocating that the
methods presented in this book are the “best” or most trendy way of building those
applications. We’ve tried to strike a balance between being modern and being pragmatic.
In the end, each of the examples should give you the core of a functioning project, touch
upon some common pain points, and show you how Rust can be used in a new domain.

1.3 Criteria for Selecting Libraries


Though Rust has already been used in many production-grade projects, it’s still a
relatively young language with constant innovation. This means it can sometimes
be a challenge to select the libraries or frameworks to use in each chapter. There are
experimental pure-Rust implementations for almost every domain, and just as many
Rust bindings of popular libraries in other languages (especially in the C and C++
spaces). In some areas, a clear leader has emerged and a particular library acts as a

3
https://www.rust-lang.org/learn

3
Chapter 1 Welcome to the World of Rust

de-facto standard. In other areas, many proof of concept packages exist without any
clear winner. The early adopters of Rust are usually adventurous developers; they are
comfortable with rough edges in the libraries and find workarounds (the Rust ecosystem
makes it easy to download and inspect the source code of any library used). Some
libraries focus on innovation and experimentation, while others value stability and
production readiness. In this book, we’re trying to demonstrate the core concepts in
each field, and how these translate into an idiomatic Rust API. Therefore, we select the
libraries we use by the following criteria.

Pure Rust
We generally try to find libraries that are built purely in Rust. Rust’s FFI (foreign
function interface) allows you to call existing C libraries (and many other languages)
from Rust. This in turn means that the easiest way to build Rust applications quickly
is often to leverage existing libraries from other languages. These libraries are usually
designed with other languages in mind, so wrapping them in Rust results in a weird and
non-idiomatic Rust API. If there is a purely Rust library or a library that uses existing
technology but is built from scratch using Rust, we tend to choose those.

Maturity
However, not every purely Rust library is very mature. Because many Rust libraries are
built from a clean slate, the developers often try to experiment with the latest technology,
and that might mean that the architecture and API design is very experimental and
changes frequently. Some libraries show great potential in their early days, but then
development slows down, and the projects eventually go into maintenance mode or
are abandoned. We aim to build useful software rather than experiment with exciting
technologies and throw the code away. Therefore, we need to be pragmatic and choose
a library that is mature enough and uses widely accepted design patterns, rather than
being dogmatic about using pure-Rust libraries. We chose to use a GTK+-based library in
Chapter 3 for this reason.

4
Chapter 1 Welcome to the World of Rust

Popularity
If two or more candidate libraries meet the preceding criteria, we’ll choose the most
popular one. The popularity is based on a combination of factors like the following:

• Number of downloads on crates.io

• Pace of development and releases

• Discussions on issue trackers and discussion forums

• Media coverage

Although popularity is not a guarantee of success, a popular project is more likely to


have a big community that supports it and keeps it alive. This can help us find a library
that has the most potential to stick around longer in the future. You are also more likely
to get support and answers online.

1.4 How to Use This Book


The chapters in this book are independent of each other, so you may read them in any
order you want. However, some of the ideas or design patterns are used in multiple
chapters. We try to introduce these ideas in the chapter where the design originated, or
where they make the most sense. For example, the concept of using event handlers to
build a responsive user interface is introduced in the “Text-based User Interface” section
in Chapter 3, and is then referenced in Chapter 7. So, reading the book from cover to
cover might help you build up this knowledge in an incremental way.

Chapters Overview
In Chapter 2, we start with the easiest application we can build with Rust: a command-­
line interface (CLI). Building a CLI requires very minimal setup and background
knowledge but can produce very powerful applications. We first introduce how to read
raw arguments using the standard library, then we show how to use Clap to manage
arguments better. We also see how to get features like generating a help message for free.
Then we touch upon topics like piping, testing, and publishing the program to crates.io.

5
Chapter 1 Welcome to the World of Rust

In Chapter 3, we build two-dimensional interfaces. We first build a text-based 2D


interface using the Cursive text-based user interface system. This allows us to build
interactive user interfaces like popups, buttons, and forms. The experience in the text-­
based user interface (TUI) paves the way for a graphical user interface (GUI). We’ll be
introducing the Rust bindings for the popular GTK+ 3 library, gtk-rs. We then build the
same interactive form using the GUI library.
In Chapter 4, we compile Rust to WebAssembly, a combination of bytecode and
sandboxed environment meant to run on platforms such as web browsers. We write
some simple WebAssembly code to offload large, heavy operations in the browser from
JavaScript to Rust. Then we explore yew-rs, a Rust front-end web framework that
lever­ages WebAssembly to create responsive single-page applications. We create a
single-­page application that can receive and display user data, maintaining state in the
web browser.
In Chapter 5, we explore Rust in the more traditional context of server-side rendered
web pages and REST APIs. We recreate the web page from the previous chapter, except
this time as a server-side page served by the Rust actix-web framework. We integrate a
Postgres database to store and retrieve user-provided data. We then modify the project to
use stand-alone REST APIs, which allows for programmatic calling of our APIs between
different web services. We further refine our project to explore testing and error handling
in the context of Rust.
In Chapter 6, we explore the cutting edge of web service development by deploying
a REST API to AWS Lambda Functions and the AWS SDK for Rust. This lets us work with
the web without individual servers. We use an AWS DynamoDB table to store user-­
provided info, and use an S3 Bucket to store larger files, with the Lambda functions
interacting with both. We then use S3 to serve a static website with callbacks into our
Lambda API, to give a complete website that deploys from a single project and scales to
massive numbers of users.
In Chapter 7, we build a game in Rust. We use the Bevy game engine to make a cat
volleyball game. You’ll learn the design philosophy and architecture behind Bevy, called
the entity-component system. You’ll also learn how to create 2D games, rendering
the characters and items with a spritesheet. We implement game logic like collision
detection, keeping score, and adding sound effects and background music.
In Chapter 8, we connect the virtual world with the physical world by introducing
physical computing on a Raspberry Pi development board. We start by installing a full
operating system and the whole Rust toolchain on the device, and introduce how to use

6
Chapter 1 Welcome to the World of Rust

Rust to control an LED and how to take inputs from a physical button. Then we show
you how to cross-compile Rust on another computer to produce a binary that runs on a
Raspberry Pi.
In Chapter 9, we shift our focus to artificial intelligence and machine learning.
We show how to implement unsupervised and supervised machine learning models
using the linfa and rusty-machine crates. For the unsupervised model we introduce
K-means, and for the supervised model we demonstrate a neural network. We also show
how to do some data-processing tasks like test data generation, reading/writing CSV
files, and visualization.
Finally, in Chapter 10, we give a broad overview of other exciting fields in Rust
that can’t fit in this book. We point you to cool projects in areas like operating systems,
programming languages, and distributed systems. This chapter acts as a guide book for
your future exploration into the vast world of Rust.

1.5 Source Code
All source code for this book is available on GitHub: https://www.github.com/apress/
practical-rust-projects-2e.
When we include source code in the book, we only highlight the parts that are
relevant to the point being discussed. The non-relevant parts will be omitted with a
comment like this:

// ...

Therefore, not all code examples can be compiled successfully. To check the fully
working example, check the source code on GitHub.
Most of the examples are developed and tested on a Linux (Ubuntu 22.04) machine.
The Rust version is stable-x86_64-unknown-linux -gnu - rustc 1.68.2. The stable
version is used as much as possible, but certain libraries might require us to use the
nightly version.

7
Visit https://ebookmass.com today to explore
a vast collection of ebooks across various
genres, available in popular formats like
PDF, EPUB, and MOBI, fully compatible with
all devices. Enjoy a seamless reading
experience and effortlessly download high-
quality materials in just a few simple steps.
Plus, don’t miss out on exciting offers that
let you access a wealth of knowledge at the
best prices!
Other documents randomly have
different content
Suddenly the canopy over the stern-walk vibrated violently. The
watchers instantly drew back and laid themselves flat on the deck.
The next instant the dark outline of a man appeared above the
metal covering of the stern-walk. It was Schneider.

The man was active in spite of his obvious cowardice, for with the
utmost dispatch he passed the heavy snatch-block over the hempen
cable that connected the two vessels and closed its hinged side.

From the hook of the block was a bo's'un's chair. On this the rogue
adroitly took his seat, and instantly let go. So cunningly had he laid
his plans that he had omitted no detail to ensure success, for the
sheave made no sound as the block descended the bight of the
hawser, showing that he had not forgotten to oil the large lignum-
vitae roller.

"Wait till he reaches the middle of the slack," ordered the captain.
Then, having ascertained by the aid of his glasses that the fugitive
was dangling a few feet from the water midway betwixt the Olive
Branch and the German vessel, he whipped out a knife and
proceeded to sever the hawser.

"Good heavens!" muttered Jack Stockton under his breath. "It's


murder!"

"No fear; he'll only get a ducking. They'll haul him inboard by
means of the whip," replied Gerald. "Stand by and look out for the
hawser when she goes."

The warning had hardly been given when the last strands of the
stout cable snapped, the inboard portion flying across the deck.
Then, like a greyhound released from its leash, the Olive Branch
darted off into the darkness.

"Pass the word for the searchlight to be run," ordered Captain


Brookes. "Hard a-starboard with the helm."
Round spun the cruiser. Her giant beams swept the gently heaving
water, and revealed the tramp, like a silver bark, lying well-nigh
motionless a couple of miles away on the starboard bow.

"That will do. Keep yonder craft in sight," continued Captain


Brookes. "Now gentlemen, we'll retire. To-morrow morning I'll finish
up this business."

At daybreak Gerald went on deck, eager to learn the state of


affairs, and found that Captain Brookes had already forestalled him.

Less than a mile away was the German vessel. Her crew had taken
the severed cable on board, and had doubtless discovered that the
parting of the tow-rope was caused by a deliberate act, for they had
hoisted a staysail and trysail, and were heading slowly S.S.W.

In obedience to the captain's order the Olive Branch was brought


within hailing distance of the vessel she had befriended, and had in
return received such despicable treatment.

"Heave-to," thundered Captain Brookes. "I'm going to send a


boat."

"Mr. Slade," he added, addressing one of the lieutenants, "you will


please board yonder craft and bring back Mr. Taylor at any cost. Mr.
Tregarthen, will you also accompany Mr. Slade?"

The gig's crew scrambled into the boat with alacrity. Every man
was armed with a [110] cutlass, while from their somewhat
exaggerated holsters peeped the butts of revolvers. The lieutenant
was also provided with a pistol, but Gerald preferred to go unarmed.

As the boat drew near to the foreigner the bulwarks of the latter
were lined with fair-complexioned, stolid-faced Germans, but no
attempt was made on their part to encourage the men of the cruiser
to board.
"Throw us a line, will you?" shouted Slade.

"What do you want?" demanded the master of the tramp.

"We want the person who deserted from our ship last night. We
know that you aided and abetted him," replied the lieutenant.

"You no come aboard my ship," retorted the master, resolutely.


"See dis flag; dis ship German territory," and he pointed aft to where
the red, white, and black ensign fluttered from the staff.
[Illustration: The man staggered, clapped his hand to his shoulder, and fell to the
deck, the weapon slipping from his grasp.]

"In bow! Oars!" ordered the lieutenant, and the boat ran alongside
the towering wall-sided hull.

Taking advantage of the roll of the ship the bowman managed to


obtain a hold with his boathook on the iron bulwarks. The next
instant a sweep with a hatchet severed the head of the boathook
and a lump of coal was hurled into the boat. Fortunately it struck
one of the thwarts, which prevented the little craft from being stove
in.

Slade's face darkened with anger. [111]

"Do that again, and I'll fire," he shouted. At this threat the Teutonic
skipper leant over the bridge rails and flourished a revolver. "You
pirates!" he drawled. "Stand off, or me fire!"

Then, on giving an order to his men, the cruiser's boat was saluted
by a volley of coal and scraps of iron, some of the boat's crew
receiving nasty injuries.

This was more than the lieutenant could stand. Without another
moment's hesitation he drew his revolver, took a rapid aim, and
pressed the trigger.

There was no flash, no noise, only a slight twitching of the


lieutenant's arm as the powerful weapon kicked; but Tregarthen saw
the German stagger, clap his hand to his shoulder, and fall to the
deck, his weapon slipping from his nerveless grasp.

"Now, lads, away boarders!"

Aghast at the fall of their skipper, and still more astounded at the
silent messenger that had laid him low, the crew of the tramp
offered little resistance, and in a few minutes the cruiser's people
were in possession of the tramp's deck.

In response to a signal a second boat left the Olive Branch,


containing the surgeon in addition to an armed party. Examination
showed that the German master's wound was not serious, the bullet
having passed completely through the fleshy part of his shoulder;
and having attended to the wounded man, Dr. White ordered his
removal to his cabin.

"Look here, Tregarthen," exclaimed Slade, "you speak their lingo;


tell the first mate to muster his men on deck, or there'll be more
trouble."

Thoroughly cowed, the German obeyed, and the crew having fallen
in on the upper deck, Slade told off a party of his men to search the
Afrika, for that was the name of the vessel. A prolonged search
revealed no trace of the missing scientist. The mate was sullen
under examination, and for a time neither requests nor threats were
of any use.

At length, unable to curb himself, Slade drew his revolver and


pointed it at the man's head, bidding Gerald to inform him that
Taylor must be produced, dead or alive, within five minutes.

Whether the lieutenant meant to keep his word or not his grim
determined features compelled the mate to give way, and in
response to a guttural order two of his crew, accompanied by four of
the cruiser's men, descended to the fore-peak.

The deserter was discovered hidden in an empty tank, and in spite


of his strenuous resistance he was brought on deck and
unceremoniously bundled into the gig. Then, having achieved the
object of their mission, the two boats' crews pulled back to the
cruiser.
"Take him below and lock him in his cabin," ordered Captain
Brookes, sternly. "Let two men remain with him in case he tries to
injure himself. Mr. Tregarthen," he added, "I have to thank you for
your assistance in the matter. No doubt you are in need of a meal;
your breakfast awaits you."

"I wonder why the captain was so keen on seeing that I had my
breakfast?" remarked Gerald to his friend Jack as the pair attacked
their meal.

"Goodness only knows," replied Stockton, who had already been


acquainted with the details of the visit to the Afrika. "But, by jove, if
that man calls himself the Exterminator of War, all I can say is he's
going a funny way to work. It will end with the Olive Branch being
denounced as an ocean pariah, and we shall all be hanged."

"It's certainly an act of piracy," assented Gerald. "I should not be


surprised if within a week an international squadron is sent in pursuit
of us. Yes, Jack, it's rank piracy."

And even while Tregarthen was thus expressing himself, Captain


Brookes, with the coolest audacity imaginable, had hoisted the white
ensign to the gaff as the Olive Branch glided rapidly away from the
outraged German ship.
[40]

BY PERCY F.
WESTERMAN
Author of "A Lad of Grit," etc.

ILLUSTRATED BY E. S. HODGSON

Synopsis

GERALD TREGARTHEN, sub-


lieutenant of H.M.S. Calder, being
on leave, sails from Poole with his
old school chum Jack Stockton on
board the latter's yacht Playmate.
In mid-Channel the yacht is run
down; the two friends are
rescued, and find themselves on
board a mysterious cruiser—the
Olive Branch—commanded by
Captain Brookes. Finding that Tregarthen is a British naval officer,
Captain Brookes announces his intention of keeping him on board,
and, after due deliberation, Gerald decides to fall in with the
captain's plans, as far as his sense of loyalty will permit.
Tregarthen is initiated into the secrets of the Olive Branch,
including that of the deadly ZZ-rays—an irresistible charge of
electricity whereby the destruction of a hostile ship can be effected
at will. Captain Brookes also explains that by the power at his
command he hopes to make war so terrible that no nation will
venture to declare war; thus universal peace will be assured.

During the voyage south Schneider, the ship's scientist, deserts,


taking with him some important plans. He is found on board a
German "tramp," and is brought back to the Olive Branch, whereby
an act of piracy is committed.

CLEARED FOR ACTION

I T was six bells in the forenoon watch. The Olive Branch, her speed
reduced to a bare ten knots, slipped noiselessly through the oily
waters, the tropical sun beating down fiercely upon the awning that
had been spread over the quarter-deck.

Seated upon chairs abaft the after-turret were the ship's officers,
while on either hand were mustered as many of the crew as could
be spared from their duties. There was an air of sternness about the
assembly, for Taylor, the scientist, was about to be tried on a charge
of desertion and treachery.

"Bring in the prisoner!" ordered the captain, and escorted by two


armed seamen the culprit was marched on deck and directed to take
up a position facing his judges.

"Mark Taylor," exclaimed Lieutenant Palmer, who appeared as


prosecutor, "you are accused upon direct evidence of having broken
out of this vessel and having sought to obtain a refuge on board the
German ship Afrika. That in itself is a serious charge; but not
content with that breach of discipline you wittingly informed the
master of the aforesaid Afrika of the secrets appertaining to the
ordnance of this cruiser, the Olive Branch. Do you plead guilty or not
guilty?"

"Not guilty," replied the accused man, with a forced tone of


defiance. "I——"

"That will be sufficient for the present," said the lieutenant. "Your
evidence will be taken in due course."

Five witnesses for the prosecution having been called, the prisoner
was allowed to speak on his own behalf.

The accused scientist tacitly admitted that he had broken out of the
ship, but strenuously denied having given any information regarding
[145] the cruiser to the master or any member of the crew of the
Afrika. At first his speech was delivered in perfectly pure English, but
by degrees he waxed excitable and spoke with a decided foreign
accent.

"And I claim," he continued, "ze protection of ze German flag, for I


am a German by nationality."

"Is that so?" demanded Captain Brookes. "How is it that this fact
was concealed when you joined this vessel? And why has it
remained a secret till this moment?"

"I am a German," reiterated the prisoner. "My name is Schneider,


not Taylor. I told zese gentlemen it was so," indicating Gerald and
Jack with a wave of his hand. "I told zem I was a German subject,
and zat I was about to run away from ze ship as soon as I was able,
and zey know it."

"Then why did you not report this to me, sir?" asked Captain
Brookes, turning to Gerald.

"The man came into my cabin one evening in an excited manner,"


replied Gerald, calmly. "He certainly said his name was Schneider,
and began to tell us a long rigmarole concerning his private affairs.
We told him that if he had a grievance, you, sir, were the best
person to hear it. With that we kicked him out."

"Thank you," said Captain Brookes, and, addressing the prisoner,


continued, "Are you in a position to inform us where are the
drawings and specifications relating to the 6in. shells?"

The accused turned a shade paler than before.

"In one of ze lockers in ze laboratory," he replied.

"If I send you to the laboratory under escort, can you produce
them?"

"Hein! If zey are not zare zey haf been stolen," exclaimed
Schneider. "Perhaps you haf hidden zem."

"They have been stolen, sir," rapped out the captain, harshly; "and
by you. They were found in the cabin of the master of the Afrika by
Lieutenant Slade. What have you to say to this?"

Schneider's limbs were trembling so violently that one of the


seamen had to support him, otherwise he would have fallen to the
deck.

"Well, gentlemen, your verdict?"

"Guilty on both counts."


"Mark Taylor, otherwise Schneider, you stand convicted on charges
of desertion and treachery. With reference to the first crime I now
admit that you are a German subject, and that I was in error in
removing you from the protection of the German flag. However, the
mischief is done, and I must abide the consequences, though I fear
not the whole naval force of that Empire. As to your traitorous act, I
can only point out that while in my pay and holding a position of
trust on board this cruiser you wilfully betrayed your position as a
responsible officer of the Olive Branch. In every community
treachery against the supreme authority is punishable by death, and
it is in my power to inflict that penalty upon you. As, however, your
wretched crime has failed to achieve its object, and these drawings
are again in our possession, I will waive the capital punishment. You
are sentenced to solitary confinement, with sufficient exercise for the
maintenance of your health, as long as the Olive Branch remains in
commission. Remove the prisoner."

Escorted by the two armed sailors, Schneider was led from the
quarter-deck. Grimly defiant, he marched between his guards, till on
arriving at the companion ladder one of the men preceded him, the
other stepping one pace in the rear.

The prisoner descended two steps, then, suddenly turning, he


butted the seaman at the head of the ladder. The man fell, and
Schneider, seizing his advantage, sprang over his prostrate body,
cleared the rail with a single bound, and leapt into the sea.

There was a rush to the side to see the termination of the tragedy,
but the luckless man was never seen again.

"That has saved us a great deal of trouble," said Captain Brookes;


"unless the mischief's already done," he added, under his breath.

On the following day the Olive Branch was running off the east
coast of Patagonia, the rugged barren heights of that inhospitable
country being plainly visible on the starboard hand.
"Ah, good morning, Mr. Tregarthen," exclaimed Captain Brookes as
Gerald made his appearance on deck. He spoke with an affability
that had been missing during the last few days, but on this particular
morning his customary geniality seemed to have reasserted itself.
"At last I think that this vessel is fit for action; that is, as far as her
armament is concerned. Of course, there may be failures, but these
can be easily rectified. I mean to make an experiment to
demonstrate the [146] power of the Olive Branch, beyond that of her
electrical means of offence. In another hour we ought to sight Carlos
Rock—you've heard of that, perchance?"

"No, sir," replied Gerald.

"Carlos Rock is a small uninhabited island of less than a quarter of


a mile in extent, and towering to a height of 600ft. How many
rounds from a 13.5in. gun would demolish it, do you think?"

"I cannot say, sir; but one hit would make a great difference in its
appearance."

"Then you'll have an opportunity of seeing what our 6in. gun will
do. By the bye, why are most of the British Dreadnoughts able to
fire two more guns astern than they can ahead."

"Merely the result of circumstances," replied Tregarthen, bridling


under the sting of the suggestion. "The position of the after-turrets
is to facilitate the broadside fire."
[Illustration: Schneider cleared the rail, and leapt into the sea.]

"Other nations may not think so."


"They can think what they like, sir," replied Gerald.

"So they can, so they can," rejoined Captain Brookes, with an air of
a man wishing to remove a wrong impression. "Now, if you will
accompany me to the conning-tower, we'll see what's to be done."

The order for general quarters was given by means of a bugle-call,


and in a few minutes the scanty crew of the Olive Branch were
busily engaged in un-shipping stanchions and rails. Then, in
response to another order the decks were deserted.

"Do they call this 'cleared for action,' I wonder?" thought


Tregarthen, but barely had his mind expressed the thought ere
Captain Brookes thrust home a pair of levers. Silently the massive
steel windshields athwartships sank flush with the deck; the funnel
dropped out of sight; the steel boats and other deck lumber
disappeared into yawning cavities prepared for their reception; while
simultaneously every watertight door in the ship was hermetically
sealed. From end to end of the upper deck everything was cleared,
save for the four turrets, the light quick-firers, and the massive
conning-tower.

"How's that?" asked Captain Brookes, enthusiastically. "Here we are


cleared to rapid torpedo-boat attack. Now, watch while I move this
lever." [147]

This time the light quick-firers disappeared below the armoured


deck, leaving only the principal armament, while heavy steel plates
slid noiselessly over the pits into which they had vanished.

"This is where we score again. In modern battleships most, if not


all, of the light torpedo-repelling armament is badly protected. In a
general engagement the lighter guns would be dismounted in five
minutes, and the ship would fall an easy prey to a torpedo-boat
attack, especially if carried out with a combined dash. Here the guns
are ready whenever they are required. Now, here's Carlos Rock."
Gerald glanced ahead and saw a mass of stone rising almost
perpendicularly from the sea, its base lashed by the milk-white surf
that pounded incessantly upon its iron-bound shores.

Meanwhile Captain Brookes had given directions to the


quartermaster to encircle the rock at a distance of two miles so as to
make sure that it was inhabited by no human beings. Ten minutes
were sufficient for this manoeuvre, during which time the occupants
of the conning-tower swept the desolate-looking island with their
glasses; but beyond the presence of myriads of sea-birds the rock
showed no signs of life.

"Now, stand by!" exclaimed the captain to Gerald. "I cannot go into
details, but you will easily follow what I mean. All eight guns are
coupled, ready to fire a broadside. You see those three index-hands?
One shows the speed of the ship, the second the range of the object
to be fired at, and consequently the required elevation, the third
corrects the effect of windage. When set, a resultant pointer fitted
with telescopic sights gives us the correct aim. Stand here and look
through this aperture."

Tregarthen did so, and at that moment Captain Brookes depressed


the firing-key. Instantly there was a slight tremor throughout the
ship, an almost imperceptible recoil, and then a thin haze of
brownish smoke, but no noise was audible save the shriek of the
projectiles as they left the muzzle with a velocity of 2,500ft. per
second. Four seconds later the whole face of Carlos Rock was
covered by a dense cloud of dust, and with a dull rumble thousands
of tons of rock slid into the sea.

"You've altered Carlos's features, sir," exclaimed Gerald, when he


had recovered from the effects of watching this wonderful broadside.

"Ay!" assented Captain Brookes. "What ship would stand up to


that, d'you think? Now you can go below and watch the loading
operations, for we are going to keep up a rapid fire for half a
minute."

Descending a spiral steel ladder which led from the conning-tower


to below the armoured deck, Tregarthen found nearly the whole of
the ship's company, including those men whom he knew to be
captains of turrets. Why the latter should be away from the turrets
he could not quite understand.

Seamen, stripped to the waist, were running small trucks laden


with shells from the after-magazine. These were placed in a metal
hopper at a position corresponding with the base of the foremost
turret. When twelve rounds had been deposited in this hopper its
doors were closed, and a red light instantly appeared in a dial
overhead.

Once again a slight jar shook the ship, followed by eleven others in
less than twice that number of seconds. The next instant the hopper
door fell open and twelve empty and still smoking cylinders fell upon
the floor; a seaman dashed a bucket of water into the compartment,
and the work of reloading was repeated.

Then a bugle sounded the "Cease fire," and the officers returned
on deck to observe the effects of the terrible ordnance of the Olive
Branch.

"How's that for going into action?" asked Captain Brookes. "With
the exception of three men and myself all hands were safe beneath
the armoured deck. Automatic loading and firing, unerring aim, and
the victory's won, eh?"

"I certainly should not like to be on board a craft that received one
round from those guns, sir," replied Gerald. "But suppose, in the
heat of an engagement, one pair of guns was trained so that some
portion of this ship intercepted the line of fire?"
"That has been arranged for," said the captain. "Directly the arc of
fire on one pair of guns is exceeded, that turret remains locked till
the other guns are trained backward sufficiently for that pair to be
automatically linked up, so that damage to our own ship from that
cause is impossible. Of course, if necessary, each turret can be
worked independently, and in that case the captains of the guns
would have the control of the firing arrangements."

Further conversation was interrupted by the arrival of a signalman.


[148]

"Wireless message just received, sir," he reported, handing a


sealed envelope to the captain with a salute.

Captain Brookes broke open the envelope, and read and reread its
contents without moving a muscle; then he beckoned to those of the
officers who happened to be on the quarter-deck.

"Gentlemen," he exclaimed, "a wireless of extreme importance has


just been handed to me. The captain of the Afrika has reported an
outrage by a ship flying the White Ensign, and representations have
been made by the German Ambassador in London. The British
Government has rightly repudiated the suggestion that the
delinquent was a British man-of-war, and has asserted that, from the
description given, it can only be the ex-Brazilian cruiser Almirante
Constant. Consequently the British and German Governments have
issued a joint note branding that vessel as a pirate, and have stated
their intention of hounding her down at all costs, and invite the
navies of all nations to join them in their task. So, gentlemen, the
Olive Branch is a modern buccaneer. Every port and harbour is
closed against her. However, I'll stick to my purpose, but, rest
assured, I will never fire a shot against a British ship—I'll trust to the
Olive Branch's speed to shake off pursuit. But"—here his face
clouded ominously—"should a vessel of any other nationality attempt
to interfere with us, I'll give her a fair warning. If she persist, by
Jove, I'll blow her sky high!"
WIPED OUT

ALMOST without further incident the Olive Branch arrived off the
coast of Chili. Hostilities had broken out between that State and
her old rival, Peru, but beyond a few encounters between outposts
on the frontier, no serious fighting had yet taken place. Both
republics were unwilling to undertake the risk of sending an army
into hostile territory until the safety of their respective seaboards
was assured, and every day news of a decisive engagement between
the rival fleets was expected.

Directly the Olive Branch was in touch with Captain Brookes's agent
at Antofagasta a wireless message was despatched in the form of an
ultimatum to the Presidents of Chili and Peru, stating that unless the
two fleets returned to their respective ports and peace were
declared within three days, the Olive Branch would be compelled to
intervene.

The ultimatum was duly presented, and a copy appeared in the


leading newspapers of the two republics. People began to ask,
"What is the Olive Branch? And what is her nationality?" Then
someone suggested that the message was the work of either a
practical joker or a lunatic, and the heads of the two republics
treated the message with contempt. Not for one moment did anyone
connect the Olive Branch with the ex-Brazilian cruiser that had
committed an outrage upon the German flag off the port of
Pernambuco. The very idea of a vessel being able to travel from that
port to Valparaiso—a distance of 4,600 miles—in less than four days
never entered into anyone's head, and when the journal El Mundo
broadly hinted that it was a ruse on the part of the Peruvians to
frighten the antagonists, the Chilian fleet immediately put to sea.

This news was communicated to the Olive Branch from


Antofagasta, followed by the information that the Peruvian fleet had
steamed out of Callao, bound south.

"Now we'll have them!" exclaimed Captain Brookes. "We'll get in


touch with the Chilian vessels first, then pass them hull down so as
to get between the two fleets. This done I hold them in the hollow
of my hand." Unfortunately for Captain Brookes his plans were
doomed to failure. The fleet of the Southern Republic was sighted
and passed as arranged, but in the interval the Peruvian squadron
had altered its course and was steaming for Iquique.

"There they are," announced Captain Brookes, late one afternoon,


pointing to a dense haze that obscured the otherwise clear horizon.

"Not much mistake about that, sir," assented Tregarthen. "If those
vessels are not burning Lota coal, I'm a Dutchman!"

"It's too late to do anything much to-day," added the captain. "I'll
give them a dose of Z-rays, and during the night we'll slow down
and hang on their flanks. To-morrow we'll press the business."

Throughout the night the Peruvian fleet, unable to use searchlights


and night-sights, pounded along, keeping an erratic compassless
course towards Iquique. Unable to explain the cause of the sudden
failure of their electrical gear, the officers and men were in a state
[149] of nervous tension, expecting every moment to find the Chilian
fleet at their heels.

Just before daybreak the Olive Branch, to avoid being influenced by


the Z-rays that permeated the fleet, put her helm hard over in order
to allow the fugitives to gain a few miles.
As she did so a violent explosion shook the ship from stem to stern,
and a huge column of water sprang up from alongside her starboard
quarter.

"A mine, by Jove!" exclaimed Gerald.

He was right. The Peruvians had strewn the sea with mines as they
fled for shelter, and, on turning, the Olive Branch's starboard
propellers had struck the dangerous weapon.

There was no panic. Every man was at his post, cool and alert. The
carpenter came on deck with the reassuring statement that the
vessel was not making water, but on the other hand the engineer
reported that the three starboard propellers were useless, and that
the motors actuating them had to be shut off. Thus with only the
three port propellers working, the speed of the Olive Branch was
reduced to a bare fifteen knots.

"I'll make them pay for this!" exclaimed Captain Brookes, coolly.
"Keep her as she is, and at daybreak I'll show them what the Olive
Branch is capable of doing."

The short twilight changed into day, and the rising sun revealed the
presence of the Peruvian fleet barely seven miles to the eastward.

There were four armoured cruisers—the Santa Rosa, Lima,


Independencia, and Restauracion, the first three built at Elswick, and
the last-named having been constructed at Stettin—and three
gunboats. The latter were the lame ducks of the fleet, and in order
to protect them the speed of the cruisers had to be reduced from
twenty-three to fourteen knots.

But to the surprise of everyone on board the Olive Branch the


Independencia turned and steamed straight for the solitary and
apparently foolhardy pursuer, the Restauracion supporting her at
three cables' length on her port quarter. Throughout the night the
Olive Branch had been cleared for action, and all that was necessary
now was for the men to go to their stations.

"She's too near to use the ZZ-rays," observed Captain Brookes to


Gerald, who, at the former's request, had accompanied him to the
conning-tower. "I've given orders for independent firing the moment
she shows her teeth."

On came the Independencia, the foam flying from her bows, her
funnels emitting dense clouds of smoke, while no less than five red
and white national ensigns flew from her mast-heads and signal
yard-arms.

Suddenly her forward 4.7in. Canet gun opened fire, and a huge 45-
pounder came hurtling through the air. Fascinated, Gerald watched
its approach, unable to tear himself away from the slit in the steel
walls, though the projectile was apparently making straight for the
conning-tower. Often from behind a gun had he watched the flight of
a shell, but now the conditions were reversed.

The next thing he was aware of was a tremendous crash overhead,


followed by the fall of splintered steel and a dense suffocating
smoke.

"That's settled the charthouse and bridge," remarked Captain


Brookes as calmly as if discussing some triviality, then, pressing an
electric push, he gave orders for the forward turret to open fire.

The two 6in. weapons were discharged simultaneously, their


noiselessness contrasting vividly with the rapid detonation of the
Peruvian gun.

The doomed vessel was instantly swept out of existence. The


massive, yet graceful, outlines of the cruiser seemed to melt into a
hundred thousand fragments, then as the smoke slowly drifted, no
trace of the Independencia was visible, only an ominous swirl in the
agitated waters as the disintegrated hull plunged to its ocean grave.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like