100% found this document useful (4 votes)
43 views

Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications (2nd ed.) 2nd Edition Shing Lyu 2024 Scribd Download

Machine

Uploaded by

dehenshigacp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
43 views

Practical Rust Projects: Build Serverless, AI, Machine Learning, Embedded, Game, and Web Applications (2nd ed.) 2nd Edition Shing Lyu 2024 Scribd Download

Machine

Uploaded by

dehenshigacp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Download the Full Version of ebook for Fast Typing at ebookmass.

com

Practical Rust Projects: Build Serverless, AI,


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

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

OR CLICK BUTTON

DOWNLOAD NOW

Download More ebook Instantly Today - Get Yours Now at ebookmass.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Practical Rust Projects - Second Edition Shing Lyu

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

ebookmass.com

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/
ebookmass.com

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/
ebookmass.com

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/
ebookmass.com
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/

ebookmass.com

Practical Machine Learning on Databricks (1st Edition)


Debu Sinha

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

ebookmass.com

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/
ebookmass.com

Machine Learning for Healthcare Applications Sachi Nandan


Mohanty

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

ebookmass.com

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/
ebookmass.com
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
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
Discovering Diverse Content Through
Random Scribd Documents
With something vital in her, like those flowers
That on our desolate steppes outlast the year.
Resembles you in some things. It was that
First made us friends. I do her justice, see!
For we were friends in that smooth surface way
We Russians have imported out of France.
Alas! from what a blue and tranquil heaven
This bolt fell on me! After these two years,
My suit with Ossip Leminoff at end,
The old wrong righted, the estates restored,
And my promotion, with the ink not dry!
For those fairies which neglected me at birth
Seemed now to lavish all good gifts on me—
Gold roubles, office, sudden dearest friends.
The whole world smiled; then, as I stooped to taste
The sweetest cup, freak dashed it from my lips.
This very night—just think, this very night—
I planned to come and beg of you the alms
I dared not ask for in my poverty.
I thought me poor then. How stript am I now!
There’s not a ragged mendicant one meets
Along the Nevski Prospekt but has leave to tell his love,
And I have not that right!
Pauline Pavlovna, why do you stand there
Stark as a statue, with no word to say?

She. Because this thing has frozen up my heart.


I think that there is something killed in me,
A dream that would have mocked all other bliss.
What shall I say? What would you have me say?

He. If it be possible, the word of words!

She (very slowly). Well, then—I love you. I may tell you so
This once, ... and then forever hold my peace.
We cannot stay here longer unobserved.
No—do not touch me! but stand further off, and
Seem to laugh, as if we jested—eyes,
Eyes, everywhere! Now turn your face away....
I love you.

He. With such music in my ears I would death found me.


It were sweet to die listening! you love me—prove it.

She. Prove it—how? I prove it saying it. How else?

He. Pauline, I have three things to choose from; you shall choose.
This marriage, or Siberia, or France.
The first means hell; the second, purgatory;
The third—with you—were nothing less than heaven!

She (starting). How dared you even dream it!

He. I was mad. This business has touched me in the brain.


Have patience! the calamity’s so new.
(Pauses.) There is a fourth way, but the gate is shut
To brave men who hold life a thing of God.

She. Yourself spake there; the rest was not of you.

He. Oh, lift me to your level! So I’m safe.


What’s to be done?

She. There must be some path out. Perhaps the Emperor—

He. Not a ray of hope! His mind is set on this with that insistence
Which seems to seize on all match-making folk—
The fancy bites them, and they straight go mad.

She. Your father’s friend, the metropolitan—


A word from him....

He. Alas, he too is bitten!


Gray-haired, gray-hearted, worldly-wise, he sees
This marriage makes me the Tsar’s protégé
And opens every door to preference.
She. Think while I think. There surely is some key
Unlocks the labyrinth, could we but find it.
Nastasia!

He. What, beg life of her? Not I.

She. Beg love. She is a woman, young, perhaps


Untouched as yet of this too poisonous air.
Were she told all, would she not pity us?
For if she love you, as I think she must,
Would not some generous impulse stir in her,
Some latent, unsuspected spark illume?
How love thrills even commonest girl-clay,
Ennobling it an instant if no more!
You said that she is proud; then touch her pride,
And turn her into marble with the touch.
But yet the gentler passion is the stronger.
Go to her, tell her in some tenderest phrase
That will not hurt too much—ah, but ’twill hurt!
Just how your happiness lies in her hand
To make or mar for all time; hint, not say,
Your heart is gone from you, and you may find—

He. A casement in St. Peter and St. Paul


For, say, a month; then some Siberian town.
Not this way lies escape. At my first word
That sluggish Tartar blood would turn to fire
In every vein.

She. How blindly you read her,


Or any woman! Yes, I know, I grant
How small we often seem to our small world
Of trivial cares and narrow precedents—
Lacking that wide horizon stretched for men—
Capricious, spiteful, frightened at a mouse;
But when it comes to suffering mortal pangs,
The weakest of us measures pulse with you.
He. Yes, you, not she. If she were at your height!
But there’s no martyr wrapt in her rose flesh.
There should have been; for Nature gave you both
The self-same purple for your eyes and hair,
The self-same Southern music to your lips,
Fashioned you both, as ’twere, in the same mold,
Yet failed to put the soul in one of you!
I know her willful—her light head quite turned
In this court atmosphere of flatteries;
A Moscow beauty, petted and spoiled there,
And since, spoiled here; as soft as swan’s down, now,
With words like honey melting from the comb,
But being crossed, vindictive, cruel, cold.
I fancy her between two rosy smiles,
Saying, “Poor fellow, in the Nertchinsk mines!”

She. You know her not.


Count Sergius Pavlovich, you said no mask
Could hide the soul, yet how you have mistaken
The soul these two months—and the face to-night. (She removes
mask.)

He. You!—it was you.

She. Count Sergius Pavlovich, go find Pauline Pavlovna—she is


here—
And tell her that the Tsar has set you free. (Goes out hurriedly.)

GUNGA DIN
By Rudyard Kipling

You may talk o’ gin and beer


When you’re quartered safe out ’ere,
An’ you’re sent to penny-fights an’ Aldershot;
But when it comes to slaughter
You will do your work on water,
An’ you’ll lick the bloomin’ boots of ’im that’s got it.
Now in Injia’s sunny clime,
Where I used to spend my time
A-servin’ of ’Er Majesty the Queen,
Of all them blackfaced crew
The finest man I knew
Was our regimental bhisti, Gunga Din!
It was “Din! Din! Din!
You limping lump o’ brick-dust, Gunga Din!
Hi! slippery hitherao!
Water, get it! Pannee lao!
You squidgy-nosed old idol, Gunga Din.”

The uniform ’e wore


Was nothin’ much before,
An’ rather less than ’arf o’ that be’ind,
For a piece o’ twisty rag
An’ a goatskin water-bag
Was all the field equipment ’e could find.
When the sweatin’ troop-train lay
In a sidin’ through the day,
Where the ’eat would make your bloomin’ eyebrows crawl,
We shouted “Harry By!”
Till our throats were bricky-dry,
Then we wopped ’im cause ’e couldn’t serve us all.
It was “Din! Din! Din!
You ’eathen, where the mischief ’ave you been?
You put some juldee in it
Or I’ll marrow you this minute;
If you don’t fill up my helmet, Gunga Din!”

’E would dot an’ carry one


Till the longest day was done;
An’ ’e didn’t seem to know the use o’ fear.
If we charged or if we cut,
You could bet your bloomin’ nut,
’E’d be waitin’ fifty paces right flank rear.
With ’is mussick on ’is back,
’E would skip with our attack,
An’ watch us till the bugles made “Retire,”
An’ for all ’is dirty ’ide
’E was white, clear white, inside
When ’e went to tend the wounded under fire!
It was “Din! Din! Din!”
With the bullets kickin’ dust spots on the green,
When the cartridges ran out,
You could hear the front lines shout,
“Hi! ammunition-mules an’ Gunga Din!”

I sha’n’t forgit the night


When I dropped be’ind the fight
With a bullet where my belt-plate should ’a’ been.
I was chokin’ mad with thirst,
An’ the man that spied me first
Was our good old grinnin’, gruntin’ Gunga Din.
’E lifted up my head,
An’ ’e plugged me where I bled,
An’ ’e guv me ’arf-a-pint o’ water green:
It was crawlin’ and it stunk,
But of all the drinks I’ve drunk,
I’m gratefullest to one from Gunga Din.
It was “Din! Din! Din!
’Ere’s a beggar with a bullet through his spleen;
’E’s chawin’ up the ground,
An’ ’e’s kickin’ all around:
For Gawd’s sake git the water, Gunga Din!”

’E carried me away
To where a dooli lay,
An’ a bullet came and drilled the beggar clean.
’E put me safe inside,
An’ just before ’e died:
“I ’ope you like your drink,” sez Gunga Din.
So I’ll meet ’im later on
At the place where ’e is gone—
Where it’s always double drill and no canteen;
’E’ll be squattin’ on the coals,
Givin’ drink to poor damned souls,
An’ I’ll get a swig in hell from Gunga Din!
Yes, Din! Din! Din!
You Lazarushian-leathern Gunga Din!
Though I’ve belted you and flayed you,
By the livin’ God that made you,
You’re a better man than I am, Gunga Din!

THE TRUE BALLAD OF THE KING’S SINGER


By Helen Hunt Jackson

The king rode fast, the king rode well,


The royal hunt went loud and gay,
A thousand bleeding chamois fell
For royal sport that day.

When sunset turned the hill all red,


The royal hunt went still and slow;
The king’s great horse with weary tread
Plunged ankle-deep in snow.

Sudden a strain of music sweet,


Unearthly sweet, came through the wood;
Up sprang the king, and on both feet
Straight in his saddle stood.

“Now, by our lady, be it bird,


Or be it man or elf that plays,
Never before my ears have heard
A music fit for praise!”

Sullen and tired, the royal hunt


Followed the king, who tracked the song,
Unthinking, as is royal wont,
How hard the way and long.

Stretched on a rock the shepherd lay


And dreamed and piped, and dreamed and sang,
And careless heard the shout and bay
With which the echoes rang.

“Up, man! the king!” the hunters cried.


He slowly stood, and, wondering,
Turned honest eyes from side to side:
To him, each looked like king.

Strange shyness seized the king’s bold tongue;


He saw how easy to displease
This savage man who stood among
His courtiers, so at ease.

But kings have silver speech to use


When on their pleasure they are bent;
The simple shepherd could not choose;
Like one in dream he went.

O hear! O hear! The ringing sound


Of twenty trumpets swept the street,
The king a minstrel now has found,
For royal music meet.

With cloth of gold, and cloth of red,


And woman’s eyes the place is bright.
“Now, shepherd, sing,” the king has said,
“The song you sang last night!”

One faint sound stirs the perfumed air,


The courtiers scornfully look down;
The shepherd kneels in dumb despair,
Seeing the king’s dark frown.

The king is just; the king will wait.


“Ho, guards! let him be gently led,
Let him grow used to royal state,—
To being housed and fed.”

All night the king unquiet lay,


Racked by his dream’s presentiment;
Then rose in haste at break of day,
And for the shepherd sent.

“Ho, now, thou beast, thou savage man,


How sound thou sleepest, not to hear!”
They jeering laughed, but soon began
To louder call in fear.

They wrenched the bolts; unrumpled stood


The princely bed all silken fine,
Untouched the plates of royal food,
The flask of royal wine!

The costly robes strewn on the floor,


The chamber empty, ghastly still;
The guards stood trembling at the door,
And dared not cross the sill.

All night the sentinels their round


Had kept. No man could pass that way.
The window dizzy high from ground;
Below, the deep moat lay.

They crossed themselves. “The foul fiend lurks


In this,” they said. They did not know
The miracles sweet Freedom works,
To let her children go.

It was the fiend himself who took


That shepherd’s shape to pipe and sing;
And every man with terror shook,
For who would tell the king!
The heads of men all innocent
Rolled in the dust that day;
And east and west the bloodhounds went,
Baying their dreadful bay;

Safe on a snow too far, too high,


For scent of dogs or feet of men,
The shepherd watched the clouds sail by,
And dreamed and sang again;

And crossed himself, and knelt and cried,


And kissed the holy Edelweiss,
Believing that the fiends had tried
To buy him with a price.

The king rides fast, the king rides well;


The summer hunts go loud and gay;
The courtiers, who this tale can tell,
Are getting old and gray.

But still they say it was a fiend


That took a shepherd’s shape to sing,
For still the king’s heart is not weaned
To care for other thing.

Great minstrels come from far and near,


He will not let them sing or play,
But waits and listens still to hear
The song he heard that day.

—Copyright by Little, Brown & Co., Boston, and used by kind


permission.

THE DREAM OF CLARENCE


By William Shakespeare

O, I have passed a miserable night,


So full of ugly sights, of ghastly dreams,
That, as I am a Christian faithful man,
I would not spend another such night,
Though ’twere to buy a world of happy days,
So full of dismal terror was the time!

Methought that I had broken from the tower,


And was embark’d to cross to Burgundy;
And, in my company, my brother Gloucester;
Who from my cabin tempted me to walk
Upon the hatches: thence we looked toward England,
And cited up a thousand fearful times,
During the wars of York and Lancaster,
That had befallen us.

As we paced along
Upon the giddy footing of the hatches,
Methought the Gloucester stumbled; and, in falling,
Struck me, that thought to stay him, overboard,
Into the tumbling billows of the main.
Lord! Lord! methought, what pain it was to drown!
What dreadful noise of waters in mine ears!
What ugly sights of death within mine eyes!

Methought I saw a thousand fearful wrecks;


Ten thousand men that fishes gnawed upon;
Wedges of gold, great anchors, heaps of pearl,
Inestimable stones, unvalued jewels,
All scattered in the bottom of the sea:
Some lay in dead men’s skulls; and in those holes
Where eyes did once inhabit, there were crept,
As ’twere in scorn of eyes, reflecting gems,
Which woo’d the slimy bottom of the deep,
And mock’d the dead bones that lay scattered by.

Methought I had, and often did I strive


To yield the ghost: but the envious flood
Kept in my soul, and would not let it forth
To seek the empty, vast and wandering air;
But smothered it within my panting bulk,
Which almost burst to belch it in the sea.

My dream was lengthened after life;


O, then began the tempest of my soul,
Who pass’d, methought, the melancholy flood,
With that grim ferry-man which poets write of,
Unto the kingdom of perpetual night.
The first that did greet my stranger soul,
Was my great father-in-law, renowned Warwick;
Who cried aloud, “What scourge for perjury
Can this dark monarchy afford false Clarence?”

And so he vanished: then came wandering by


A shadow like an angel, with bright hair
Dabbled in blood; and he squeaked aloud,
“Clarence is come; false, fleeting, perjured Clarence,
That stabb’d me in the field by Tewksbury:
Seize on him, Furies, take him to your torments!”
With that, methought, a legion of foul fiends
Environ’d me about, and howled in mine ears
Such hideous cries, that with the very noise
I trembling waked, and for a season after
Could not believe but that I was in hell,
Such terrible impression made the dream.

THE BLACKSMITH OF LIMERICK


By Robert Dwyer Joyce

He grasped the ponderous hammer, he could not stand it more,


To hear the bomb-shells bursting, and thundering battle’s roar;
He said, “The breach they’re mounting, the Dutchman’s murdering
crew—
I’ll try my hammer on their heads, and see what that can do!
“Now, swarthy Ned and Moran, make up that iron well;
’Tis Sarsfield’s horse that wants the shoes, so mind not shot or
shell;”
“Ah, sure,” cried both, “the horse can wait, for Sarsfield’s on the wall
And where you go we’ll follow, with you to stand or fall!”

The blacksmith raised his hammer, and rushed into the street,
His ’prentice boys behind him, the ruthless foe to meet;—
High on the breach of Limerick with dauntless hearts they stood,
Where bomb-shells burst, and shot fell thick, and redly ran the blood.

“Now look you, brown-haired Moran; and mark you, swarthy Ned,
This day we’ll prove the thickness of many a Dutchman’s head!
Hurrah! upon their bloody path, they’re mounting gallantly;
And now the first that tops the breach, leave him to this and me.”

The first that gained the rampart, he was a captain brave,—


A captain of the grenadiers, with blood-stained dirk and glaive;
He pointed and he parried, but it was all in vain!
For fast through skull and helmet the hammer found his brain!

The next that topped the rampart, he was a colonel bold;


Bright, through the dust of battle, his helmet flashed with gold—
“Gold is no match for iron,” the doughty blacksmith said,
And with that ponderous hammer he cracked his foeman’s head.

“Hurrah for gallant Limerick!” black Ned and Moran cried,


As on the Dutchmen’s leaden heads their hammers well they plied;
A bomb-shell burst between them—one fell without a groan,
One leaped into the lurid air, and down the breach was thrown.

“Brave smith! brave smith!” cried Sarsfield, “beware the treacherous


mine!
Brave smith! brave smith! fall backward, or surely death is thine!”
The smith sprang up the rampart and leaped the blood-stained wall,
As high into the shuddering air went foeman, breach and all!

Up, like a red volcano, they thundered wild and high,—


Spear, gun, and shattered standard, and foeman through the sky;
And dark and bloody was the shower that round the blacksmith fell;

He thought upon his ’prentice boys,—they were avengèd well.

On foeman and defenders a silence gathered down;


’Twas broken by a triumph shout that shook the ancient town,
As out its heroes sallied, and bravely charged and slew,
And taught King William and his men what Irish hearts could do.

Down rushed the swarthy blacksmith unto the river’s side,


He hammered on the foe’s pontoon, to sink it in the tide;
The timber, it was tough and strong, it took no crack or strain;
“Mavrone! t’won’t break!” the blacksmith roared; “I’ll try their heads
again!”

He rushed upon the flying ranks; his hammer ne’er was slack,
For in thro’ blood and bone it crashed, thro’ helmet and thro’ jack;
He’s ta’en a Holland captain beside the red pontoon,
And “Wait you here,” he boldly cries; “I’ll send you back full soon!

“Dost see this gory hammer? It cracked some skulls to-day,


And yours ’twill crack, if you don’t stand and list to what I say;—
Here! take it to your cursèd King, and tell him, softly, too,
’Twould be acquainted with his skull if he were here, not you!”

The blacksmith sought his smithy and blew his bellows strong;
He shod the steed of Sarsfield, but o’er it sang no song;
“Ochone! my boys are dead!” he cried; “their loss I’ll long deplore,
But comfort’s in my heart, their graves are red with foreign gore.”

HYMN OF THE IMPERIAL GUARD


By Bartholomew Dowling

Up, comrades, up, the bugle peals the note of war’s alarms,
And the cry is ringing sternly round, that calls the land to arms;
Adieu, adieu, fair land of France, where the vine of Brennus reigns;
We go where the blooming laurels grow, on the bright Italian plains.
Advance! advance! brave sons of France, before the startled world;
For France, once more, her tricolor in triumph hath unfurled.

Our eagles shall fly ’neath many a sky, with a halo round their way
Where History flings, on their flashing wings, the light of Glory’s ray;
And we shall bear them proudly on, through many a mighty fray,
That shall win old nations back to life, in the glorious coming day.
Then advance, advance, ye sons of France, before the startled
world,
For France, once more, her tricolor in triumph hath unfurled.

The glowing heart of the land of Art, throbbing for Liberty,


Our swords invoke, to erase the yoke from beauteous Italy.
And the Magyar waits, with kindling hope, the aid of the Gallic hand,
To drive the hated Austrians forth, from the old Hungarian land.
Then advance, advance, ye sons of France, before the startled
world,
For France, once more, her tricolor in triumph hath unfurled.

See the Briton, pale, as he dons his mail, for the coming conflict
shock,
And before his eyes, see the phantom rise, of the Chief on Helena’s
rock;
In foreboding fears, already he hears through palace and mart anew,
Our avenging shout, o’er the battle rout—remember Waterloo!
Then advance, advance, ye sons of France, before the startled
world,
For France, once more, her tricolor in triumph hath unfurled.
And, hark, a wail from our kindred Gael, comes floating from the
West—
That gallant race, whose chosen place was ever our battle’s crest;
Now is the day we can repay the generous debt we owe
To Irish blood, that freely flowed to conquer France’s foe.
Then advance, advance, ye sons of France, before the startled
world,
For France, once more, her tricolor in triumph hath unfurled.
Old Tricolor, as in days of yore, you shall wave o’er vanquished
kings,
And your folds shall fly ’neath an English sky, on Victory’s crimson
wings;
And Europe’s shout shall in joy ring out, hailing freedom in thy track,
When our task is done, and we bear thee on, to France with glory
back.
Then advance, advance, ye sons of France, before the startled
world,
For France, once more, her tricolor in triumph hath unfurled.

THE DEATH-SONG OF THE VIKING[15]


By Bartholomew Dowling

My race is run, my errand done, the pulse of life beats low;


My heart is chill, and the conquering will has lost its fiery glow:
Launch once again on the northern main my battleship of old:
I would die on the deck, ’mid storm and wreck, as befits a Viking
bold.

I know no fears, but the mist of years that has gathered round my
track
For a moment clears, and my youth’s compeers again to my side
come back;
And the tall ships reel o’er their iron keel, as we sweep down on the
foe,
Like a giant’s form amid the storm, where the mighty tempests blow.

Again I gaze on the leaping blaze o’er a conquered city rise,


As in those days, when the Skald’s wild lays, sang the fame of our
high emprise;
When our ships went forth from the stormy North with the
Scandinavian bands
Who backward bore to the Baltic’s shore the spoil of the Western
lands.
But my race is run, my errand done; so bear me to my ship.
Place my battle-brand in this dying hand, and the wine-cup to my lip;
Then loose each sail to the rising gale and lash the helm a-lee.
Alone, alone, on my drifting throne, I would view my realm, the sea.

My realm and grave the northern wave, where the tempest’s voice
will sing
My death-song loud, where flame shall shroud the ocean’s warrior-
king,
Whilst heroes wait at Valhalla’s gate to proudly welcome me.
For my race is run, my errand done. Receive thy Chief, O Sea!

THE RIDE OF JENNIE McNEAL


By Will Carleton

Paul Revere was a rider bold—


Well has his valorous deed been told;
Sheridan’s ride was a glorious one—
Often it has been dwelt upon.
But why should men do all the deeds
On which the love of a patriot feeds?
Hearken to me, while I reveal
The dashing ride of Jennie McNeal.

On a spot as pretty as might be found


In the dangerous length of the Neutral Ground,
In a cottage cosy, and all their own,
She and her mother lived alone.
Safe were the two, with their frugal store,
From all of the many who passed their door;
For Jennie’s mother was strange to fears,
And Jennie was large for fifteen years.

One night, when the sun had crept to bed,


And rain-clouds lingered overhead,
And sent their surly drops for proof
To drum a tune on the cottage roof,
Close after a knock at the outer door,
There entered a dozen dragoons or more.
Their red coats, stained by the muddy road,
That they were British soldiers showed;

The captain his hostess bent to greet,


Saying, “Madam, please give us a bit to eat;
We will pay you well, and, if may be,
This bright-eyed girl for pouring our tea;
Then we must dash ten miles ahead,
To catch a rebel colonel abed.
He is visiting home, as doth appear;
We will make his pleasure cost him dear.”
And they fell on the hasty supper with zeal,
Close-watched the while by Jennie McNeal.
For the gray-haired colonel they hovered near,
Had been her true friend, kind and dear;
So sorrow for him she could but feel,
Brave, grateful-hearted Jennie McNeal.

With never a thought or a moment more,


Bare-headed she slipped from the cottage door,
Ran out where the horses were left to feed,
Unhitched and mounted the captain’s steed,
And down the hilly and rock-strewn way
She urged the fiery horse of gray.
Around her slender and cloakless form
Pattered and moaned the ceaseless storm;
Secure and tight, a gloveless hand
Grasped the reins with stern command;
And full and black her long hair streamed,
Whenever the ragged lightning gleamed;
And on she rushed for the colonel’s weal,
Brave, lioness-hearted Jennie McNeal.

Hark! from the hills, a moment mute,


Came a clatter of hoofs in hot pursuit;
And a cry from the foremost trooper said,
“Halt! or your blood be on your head!”
She heeded it not, and not in vain
She lashed the horse with the bridle-rein.
So into the night the gray horse strode;
His shoes hewed fire from the rocky road;
And the high-born courage that never dies
Flashed from his rider’s coal-black eyes.
The pebbles flew from the fearful race;
The rain-drops grasped at her glowing face.
“On, on, brave beast!” with loud appeal,
Cried eager, resolute Jennie McNeal.

“Halt!” once more came the voice of dread;


“Halt! or your blood be on your head!”
Then, no one answering to the calls,
Sped after her a volley of balls.
They passed her in her rapid flight,
They screamed to her left, they screamed to her right;
But, rushing still o’er the slippery track,
She sent no token of answer back,
Except a silvery laughter-peal,
Brave, merry-hearted Jennie McNeal.

So on she rushed, at her own good will,


Through wood and valley, o’er plain and hill;
The gray horse did his duty well,
Till all at once he stumbled and fell,
Himself escaping the nets of harm,
But flinging the girl with a broken arm.
Still undismayed by the numbing pain,
She clung to the horse’s bridle-rein,
And gently bidding him to stand,
Petted him with her able hand;
Then sprang again to the saddle-bow,
And shouted, “One more trial now!”
As if ashamed of the heedless fall,
He gathered his strength once more for all,
And, galloping down a hillside steep,
Gained on the troopers at every leap.
No more the high-bred steed did reel,
But ran his best for Jennie McNeal.
They were a furlong behind, or more,
When the girl burst through the colonel’s door,
Her poor arm helpless, hanging with pain,
And she all drabbled and drenched with rain,
But her cheeks as red as fire-brands are,
And her eyes as bright as a blazing star,
And shouted, “Quick! be quick, I say!
They come! they come! Away! away!”
Then sank on the rude white floor of deal,
Poor, brave, exhausted Jennie McNeal.

The startled colonel sprang, and pressed


His wife and children to his breast,
And turned away from his fireside bright;
And glided into the stormy night;
Then soon and safely made his way
To where the patriot army lay.
But first he bent, in the dim firelight,
And kissed the forehead broad and white,
And blessed the girl who had ridden so well
To keep him out of a prison-cell.
The girl roused up at the martial din,
Just as the troopers came rushing in,
And laughed, e’en in the midst of a moan,
Saying, “Good sirs, your bird has flown.
’Tis I who have scared him from his nest;
So deal with me now as you think best.”
But the grand captain bowed, and said,
“Never you hold a moment’s dread.
Of womankind I must crown you queen;
So brave a girl I have never seen.
Wear this gold ring as your valor’s due;
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