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
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
https://ebookmass.com/product/practical-rust-projects-second-edition-
shing-lyu/
https://ebookmass.com/product/practical-matlab-deep-learning-a-
projects-based-approach-2nd-edition-michael-paluszek/
https://ebookmass.com/product/practical-machine-learning-on-
databricks-1st-edition-debu-sinha/
https://ebookmass.com/product/machine-learning-for-healthcare-
applications-sachi-nandan-mohanty/
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
iii
Table of Contents
iv
Table of Contents
v
Table of Contents
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
vi
Table of Contents
vii
Table of Contents
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.
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
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
• people who already know basic Rust syntax, but want to learn how to
build applications in Rust;
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
• 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.
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:
• Media coverage
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
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.
"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.
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.
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.
"We want the person who deserted from our ship last night. We
know that you aided and abetted him," replied the lieutenant.
"In bow! Oars!" ordered the lieutenant, and the boat ran alongside
the towering wall-sided hull.
"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.
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.
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.
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.
"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.
BY PERCY F.
WESTERMAN
Author of "A Lad of Grit," etc.
ILLUSTRATED BY E. S. HODGSON
Synopsis
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.
"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.
"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?"
"Then why did you not report this to me, sir?" asked Captain
Brookes, turning to Gerald.
"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?"
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.
There was a rush to the side to see the termination of the tragedy,
but the luckless man was never seen again.
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?"
"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."
"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."
"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."
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."
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.
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.
"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."
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.
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.
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.
ebookmass.com