csperkins.org

Advanced Systems Programming H (2020-2021)

Lecture 4: Type-based Modelling and Design

This lecture discusses the concept of type-based modelling and design, and how it can be used to improve the quality of systems programs. It discusses the idea of type-driven development for structuring systems, and how this helps model the problem domain and help validate the design. And it discusses some specific examples of this, using types to model numeric values; using enumerations for alternative, options, and results; and in the modelling of state machines. Ideas around ownership tracking, how it's realised in Rust, and how it can be used to improve system design are also briefly discussed.

Part 1: Type-based Modelling and Design

The 1st part of the lecture introduces the idea of type-driven development, a way of developing software that starts by defining the types then using those to guide the development of the code and functions necessary to complete the system. It outlines why this approach is appropriate for building robust, reliable, systems programs in languages with powerful type systems, such as Rust.

00:00:00.000 The previous lectures, and the lab exercises,

00:00:02.847 have began to introduce you to Rust,

00:00:05.694 a modern strongly typed systems programming language.

 

00:00:08.641 In this lecture, I want to move

00:00:10.819 on and talk about type based modelling

00:00:12.997 and design. That is, the act of

00:00:15.174 using the type system to help with

00:00:17.352 structuring, and arranging, the design of a

00:00:19.530 program.

 

00:00:20.941 In this first part, I want to

00:00:23.047 talk about type-driven development.

 

00:00:25.351 Modern programming languages such as Rust,

00:00:27.702 which we’re using in this course,

00:00:30.053 Swift, OCaml, Scala, F#, and so on,

00:00:32.796 have very expressive type systems, and it's

00:00:35.539 possible to use the type system to

00:00:38.282 help ensure the correctness of the code

00:00:41.025 that you write.

 

00:00:42.301 One way of doing this is an

00:00:44.547 approach known as type driven development,

00:00:46.473 which was pioneered in a language known

00:00:48.719 as Idris.

00:00:49.361 The book shown on the right hand

00:00:51.707 side of the slide is is the

00:00:53.953 Idris book, which gives an introduction to

00:00:56.199 that language.

 

00:00:56.941 In a type driven development approach,

00:00:59.246 rather than structuring a program initially around

00:01:01.934 the control for flow, around what program

00:01:04.623 should do,

 

00:01:05.491 you structure it first around the types.

00:01:07.759 Think about what sorts of data,

00:01:09.704 what sort of objects, your program should

00:01:11.972 be working with, and write down the

00:01:14.241 types that describe those objects.

 

00:01:15.961 Then using the types as a guide,

00:01:18.785 write down the functions. Write the input

00:01:21.609 and output types of those functions,

00:01:24.030 validate that the design type checks and

00:01:26.854 is consistent, and then gradually refine the

00:01:29.678 functions.

 

00:01:30.181 The fundamental approach is that rather than

00:01:32.198 thinking of the types as a way

00:01:34.215 of checking the code, you think of

00:01:36.232 them as a plan, or as a

00:01:38.249 model, for the solution. And you build

00:01:40.266 up the the design around the types,

00:01:42.283 and then fill in the details of

00:01:44.300 how the operations are performed.

 

00:01:45.841 You let the types, and the compiler,

00:01:48.415 guide the structure of your design.

 

00:01:51.721 The first stage is to define the

00:01:54.011 types. That is, think of the types

00:01:56.302 which are needed to build a model

00:01:58.592 of the problem domain.

 

00:02:00.001 Think about who's interacting, what are they

00:02:02.220 interacting with, and what sorts of things

00:02:04.440 do they exchange.

 

00:02:05.491 This will likely lead you to define

00:02:07.705 types such as senders and receivers.

00:02:09.603 You may have types that represent the

00:02:11.817 connections between different entities in the system,

 

00:02:14.131 or the TCP segments being transmitted over

00:02:16.999 those connections. Or, if you're building another

00:02:19.867 type of application, you may have employees,

00:02:22.735 vehicles, or different types of cargo that

00:02:25.603 are transported in those vehicles.

 

00:02:27.751 Think about what sort of properties describe

00:02:30.512 those people and those things. And think

00:02:33.273 about what sort of data is associated

00:02:36.033 with each of them.

 

00:02:37.711 This probably leads you to types such

00:02:40.533 as email addresses, names, manufacturers. Or types

00:02:43.354 representing properties of objects, such as a

00:02:46.176 temperature, or a sequence numbers, or a

00:02:48.998 colour.

 

00:02:49.501 Think about the types of states that

00:02:51.844 the system can be in, and the

00:02:54.186 types of states the different interactions can

00:02:56.529 be in. A messaging app, or an

00:02:58.871 email client, for example, may have states

00:03:01.214 that represent the progress of sending a

00:03:03.556 message.

 

00:03:03.991 It may have a state to indicate

00:03:05.987 that it is connecting to the server,

00:03:07.982 that once it is connected that some

00:03:09.978 some sort of authentication is required or

00:03:11.974 whether it’s logged in. It may have

00:03:13.969 states to represent whether the message has

00:03:15.965 been sent, or is in the process

00:03:17.961 of sending

 

00:03:18.631 Initially, the types might very well be

00:03:21.377 ill-defined and abstract. That doesn't matter.

00:03:23.731 Write them down anyway. Refine them later.

00:03:26.476 Circle around,

 

00:03:27.361 rebuild and redevelop the types as you

00:03:29.323 get a better understanding of the problem.

00:03:31.286 The main thing, though, is to think

00:03:33.248 about what types you need to model

00:03:35.210 the problem domain.

 

00:03:36.151 And think less about the structure of

00:03:38.203 the code, and more about the structure

00:03:40.254 of the problem space, and representing that

00:03:42.306 as a set of types.

 

00:03:44.971 Once you've done that, think about the

00:03:47.317 properties that are associated with those types.

00:03:49.663 Think about the types of data which

00:03:52.009 which are associated with each of the

00:03:54.355 things in your system, and what properties

00:03:56.700 do those things have.

 

00:03:58.141 For example, a program dealing with customer

00:04:00.916 information for a shipping company might have

00:04:03.691 a sender objects that hold the name

00:04:06.466 of the customer, their email address,

00:04:08.845 and their postal address.

 

00:04:10.531 It's easy to write down such a

00:04:12.377 type, as we see on the slide.

00:04:14.223 We don't need to worry about how

00:04:16.069 a name is formatted, or an email

00:04:17.915 addresses is formatted, or a postal address

00:04:19.761 is formatted. We just note that there

00:04:21.607 is a type for that, and define

00:04:23.452 it later when we need

 

00:04:24.871 to understand the details.

 

00:04:28.441 Similarly, we think about states the various

00:04:31.300 objects are in, and we write down

00:04:34.159 types to represent the states.

 

00:04:36.301 For example, if the system is logging-in

00:04:38.791 to some some networked resource, it may

00:04:41.280 have states representing a system which has

00:04:43.770 not started connecting, and is not connected

00:04:46.260 at all;

 

00:04:47.071 a system which is in the process

00:04:49.366 of connecting to remote server; and a

00:04:51.660 system which has connected, but has not

00:04:53.955 yet authenticated; and a system which is

00:04:56.250 authenticated and logged in.

 

00:04:57.661 And, as we see in the enum

00:05:00.128 State example, it’s easy to write down

00:05:02.595 a type that represents those different aspects

00:05:05.061 of the system behaviour.

 

00:05:06.571 It may also make sense to represent

00:05:08.887 the different aspects of the behaviour,

00:05:10.872 the different states the system is in,

00:05:13.188 in different data types.

 

00:05:14.611 For example, we can model authenticated and

00:05:17.411 unauthenticated connections as two different types of

00:05:20.211 objects, both of

 

00:05:21.511 which hold the underlying TCP socket that

00:05:23.959 represents the connection to the remote resource.

00:05:26.407 But which are stored in different types

00:05:28.855 of structs, depending on what the system

00:05:31.303 is doing at the time.

 

00:05:33.151 The important thing is to write down

00:05:35.232 the types, which you can then refine

00:05:37.314 and extend as needed, as we get

00:05:39.395 a better handle on how the system

00:05:41.476 is working.

 

00:05:43.171 Once we’ve started by writing down the

00:05:45.765 types, we then move on to sketching

00:05:48.360 out functions.

 

00:05:49.201 The idea here is that by using

00:05:51.599 the types as a guide, we sketch

00:05:53.996 out the function prototypes and leave the

00:05:56.393 concrete implementation of the system until later.

 

00:05:58.891 The example on the slide shows how

00:06:01.341 one might sketch out the design for

00:06:03.791 an email client, for example.

 

00:06:05.641 An email client that has connected to

00:06:07.820 the server can be one of two

00:06:10.000 states.

 

00:06:10.411 Initially after it’s established the connection,

00:06:12.533 it will be in an unauthenticated state,

00:06:15.008 where it's connected to the server that

00:06:17.483 has not yet logged in.

 

00:06:19.351 In this state, which we represent by

00:06:21.731 the unauthenticated connection at the bottom of

00:06:24.111 the slide, the only possible actions that

00:06:26.491 can perform are to login or to

00:06:28.871 disconnect.

 

00:06:29.311 If it logs in, it needs to

00:06:31.776 provide some credentials to the server.

00:06:33.889 And, as a result of that,

00:06:36.002 it will either successfully login, returning an

00:06:38.467 authenticated connection,

 

00:06:39.271 or it will have provided the wrong

00:06:42.182 credentials, and we'll get a login error

00:06:45.093 of some sort.

 

00:06:46.441 The important thing here is that this

00:06:48.935 behaviour is reflected in the types and

00:06:51.429 the operation of the function

 

00:06:53.311 We have an authenticated connection, and we

00:06:55.828 perform a login operation on that connection,

00:06:58.345 giving it some credentials. If it succeeds,

00:07:00.862 it returns

 

00:07:01.681 an authenticated connection, a different connection type.

00:07:04.130 Once we have an authenticated connection,

00:07:06.228 we can perform the other types of

00:07:08.677 operations you may wish to perform in

00:07:11.125 an email client. You can list the

00:07:13.574 folders, you can list the messages in

00:07:16.022 a folder, and eventually you can disconnect.

 

00:07:18.571 What's important here is that the behaviour

00:07:21.069 of the system is obvious just from

00:07:23.567 looking at the function prototypes. And the

00:07:26.065 different types of object we’re dealing with

00:07:28.564 constrain the possible behaviours.

 

00:07:30.091 If we're not logged in the only

00:07:32.509 things we can do, given that we

00:07:34.928 have an unauthenticated connection, is login or

00:07:37.346 disconnect. if we are logged in,

00:07:39.419 the only things we can do is

00:07:41.837 list the folders, list the messages,

00:07:43.910 or disconnect.

 

00:07:44.701 It's perhaps obvious, but we can't try

00:07:46.764 to list the folders before we've logged

00:07:48.827 in, and we can't try to lock

00:07:50.890 it login twice. And it's not the

00:07:52.953 system prohibits us from doing this at

00:07:55.016 runtime, is that the code won’t compile

00:07:57.079 if we try to perform the operations

00:07:59.142 in the wrong state.

 

00:08:00.421 Those functions, those operations, don't exist on

00:08:03.365 the types representing the other states of

00:08:06.310 the system.

 

00:08:08.251 And this is one of the key

00:08:10.660 points of Type Driven Design. The behaviour

00:08:13.068 should be obvious from the types,

00:08:15.132 and the types should constrain the behaviour.

 

00:08:17.641 In the simplest case. This means using

00:08:20.345 specific types that model the problem domain,

00:08:23.049 rather than using generic types.

 

00:08:25.081 That is, pass a username parameter around,

00:08:27.662 rather than a string. Or pass a

00:08:30.243 temperature in Celsius type around, rather than

00:08:32.824 an integer.

 

00:08:33.661 By using the more specific types,

00:08:35.983 the compiler can check what we're doing.

00:08:38.692 It can check that the behaviours we're

00:08:41.401 doing makes sense, and can check our

00:08:44.109 design. Essentially it's machine checkable documentation.

00:08:46.431 If we structure the code wrong,

00:08:48.753 it just won't compile.

 

00:08:50.401 Similarly, as we saw on the previous

00:08:53.055 slide, encode the states as the types,

00:08:55.709 and the state transitions as functions that

00:08:58.363 manipulate those types.

00:08:59.500 The diagram shows an example state machine

00:09:02.254 for an email client.

 

00:09:03.871 You start with a pre-connection, where the

00:09:06.368 system is not yet connected to the

00:09:08.866 server. You connect, and that consumes the

00:09:11.363 pre-connection and returns a new type representing

00:09:13.861 an authenticated connection.

 

00:09:15.031 Given an authenticated connection, you can either

00:09:17.735 disconnect, which closes down the connection and

00:09:20.439 gives you back a pre-connection,

 

00:09:22.471 or you can attempt to login.

00:09:24.942 And if that's successful you'll get an

00:09:27.824 authenticated connection object. Given an authenticated connection

00:09:30.706 object, you can list folders, send and

00:09:33.589 receive email messages, are you can disconnect.

 

00:09:36.571 We see that the types represent the

00:09:39.527 state machine, and that the functions which

00:09:42.483 transition between the different states return different

00:09:45.439 types.

 

00:09:45.961 The login function, for example, consumes enough

00:09:49.725 an unauthenticated connection objects and returns an

00:09:53.488 authenticated connection object.

 

00:09:55.201 It forcibly moves the program from the

00:09:57.919 unauthenticated state to the authenticated state,

00:10:00.249 because it takes away that object and

00:10:02.968 returns the new object.

 

00:10:04.621 And the functions only get implemented on

00:10:06.918 the types where they make sense to

00:10:09.215 enforce the behaviour, enforce the logic,

00:10:11.184 enforce the state machine of the system.

 

00:10:14.581 Again, the goal is that the types

00:10:17.037 and the functions provide a model of

00:10:19.492 the system. They define what you're working

00:10:21.948 with, and how the system moves between

00:10:24.404 its various states as the different operations

00:10:26.859 are performed

 

00:10:27.661 You sketch out an initial design,

00:10:29.754 and then you iterate as you go.

00:10:32.195 Each time just filling in enough details

00:10:34.637 to keep the system compiling, and using

00:10:37.078 the compiler to check for consistency.

 

00:10:39.271 And you gradually refine the design,

00:10:41.425 you refine the types, you refine the

00:10:43.938 functions, you gradually fill out the function

00:10:46.450 bodies, until the whole system has been

00:10:48.963 modelled. And, gradually, add in the concrete

00:10:51.476 implementation details, refining as needed.

 

00:10:53.371 Essentially, what you're doing is working with

00:10:55.854 the compiler to validate the design,

00:10:57.983 before you write the detailed implementation.

 

00:11:00.211 Then, as you gradually fill in the

00:11:02.483 details of the implementation, the compiler keeps

00:11:04.754 you right. It validates your design for

00:11:07.026 correctness at all points through the operation

00:11:09.297 of the system.

 

00:11:11.371 It's an approach which is known as

00:11:14.157 correct by construction.

 

00:11:15.451 Use the types, use the type system,

00:11:18.138 to model and check the problem space

00:11:20.825 and check your design. And to debug

00:11:23.512 your design before you even begin to

00:11:26.199 run the code.

 

00:11:27.451 The idea is that nonsensical operations in

00:11:30.251 your program don't cause the system to

00:11:33.051 crash, rather they just don't compile.

 

00:11:35.551 It's a change in perspective in the

00:11:38.046 way we write code.

 

00:11:39.571 Use the type system, use the compiler,

00:11:42.606 as a model checking tool to help

00:11:45.640 validate your design.

 

00:11:47.041 Debugging should be a process of checking

00:11:50.054 the design for correctness, not finding where

00:11:53.066 the segmentation fault was.

00:11:54.788 So that concludes this part of the

00:11:58.901 lecture.

 

00:11:59.431 I've tried to introduce the idea of

00:12:02.223 type-driven design.

 

00:12:03.121 When building a system in the type

00:12:05.328 driven design approach, start by thinking about

00:12:07.534 the types, rather than the control flow.

 

00:12:09.841 Write down the types describing the system,

00:12:12.682 modelling the problem domain. Sketch out the

00:12:15.524 function prototypes, show how they transition between

00:12:18.365 the types, and gradually refine and add

00:12:21.206 detail as needed until you end up

00:12:24.047 with a working system.

 

00:12:25.771 Used to compiler and the type system

00:12:27.010 to debug your design.

00:12:27.717 In the next part of this lecture,

00:12:29.056 I’ll move on to talk about some

00:12:30.295 design persons, and show how this can

00:12:31.533 be done in practice.

Part 2: Design Patterns

Part 2 of the lecture, expands on the ideas of type-driven development, and discuss some specific design patterns. In particular, the lecture discusses the use of specific rather than generic types for numeric values; and the use of enumeration types, such as Option and Result; to being to express features of the problem domain in the code. This helps model the problem, and lets the compiler start to help check system designs for consistency and correctness.

00:00:00.000 In this second part, I want to

00:00:03.400 talk about some design patterns that can

00:00:05.800 help enable type-driven design.

00:00:07.171 In particular, I want to talk about

00:00:09.671 the use of specific numeric types to

00:00:12.071 replace generic and integer and floating point

00:00:14.471 types, and about the use of enumerations

00:00:16.871 to represent alternatives.

 

00:00:19.000 One of the key questions to ask

00:00:21.173 when building a system, according to the

00:00:23.346 type driven design approach, is whether a

00:00:25.519 numeric value is really best represented as

00:00:27.692 a floating point value or an integer,

00:00:29.865 or does it have some meaning that

00:00:32.037 could be included in the types.

 

00:00:34.000 For example, is the value actually a

00:00:36.948 temperature in degrees Celsius or degrees Fahrenheit,

00:00:39.897 a speed in miles per hour or

00:00:42.845 kilometres per hour, a user ID,

00:00:45.373 a packet sequence number, or whatever.

 

00:00:48.000 The idea is that it should be

00:00:50.077 possible to encode the meaning of a

00:00:52.153 numeric value in its type, so the

00:00:54.230 compiler can check for consistent usage of

00:00:56.307 that type.

 

00:00:57.000 Operations that mix different types should fail

00:00:59.987 if the types don't match. Or they

00:01:02.973 should perform safe unit conversions.

00:01:05.107 And operations that are inappropriate for a

00:01:08.193 type shouldn't be possible.

 

00:01:10.000 That the news article shown on the

00:01:12.336 slide gives a famous example of the

00:01:14.672 problems this sort of confusion can cause.

00:01:17.008 The software for the Mars Climate Orbiter

00:01:19.443 used metric units in some parts of

00:01:21.779 the code, and Imperial units in others,

00:01:24.115 and wasn't able to tell when the

00:01:26.451 two were being mixed up.

00:01:28.120 The result was that the spacecraft crashed

00:01:30.555 into the planet, rather than entering orbit,

00:01:32.891 wasting many hundreds of millions of dollars

00:01:35.227 and many years of work, because it

00:01:37.563 fired its thrusters for too long,

00:01:39.565 due to a miscalculation.

 

00:01:41.000 I'd argue that this type of error

00:01:43.720 shouldn't be possible. Well written code should

00:01:46.440 encode the units into the numeric types.

00:01:49.160 If your program is mixing up Pound

00:01:51.980 Force Seconds and Newton Seconds, as happened

00:01:54.700 in the Mars Climate Orbiter, the code

00:01:57.420 shouldn’t fail at runtime – it shouldn’t

00:02:00.140 compile.

00:02:01.279 The goal then, should be to represent

00:02:04.099 the different units, the different types of

00:02:06.819 numeric values, in the type system.

 

00:02:09.500 So let's make this a little bit

00:02:11.855 more concrete.

00:02:12.527 The code on the right is a

00:02:14.982 very simple example.

00:02:15.991 It sets the variable C to be

00:02:18.445 15 – the temperature in degrees Celsius,

00:02:20.800 And the variable F to be 50

00:02:23.155 – a temperature in degrees Fahrenheit.

00:02:25.173 And it then calculates the value T

00:02:27.527 as being the sum of F and

00:02:29.882 C, and prints out the result.

 

00:02:32.000 It prints out the value of 65.

00:02:34.638 The sum of 50 and 15.

 

00:02:37.000 And, numerically, this makes sense. However,

00:02:39.700 as a programmer, we know that it's

00:02:42.850 actually giving the wrong answer. Unfortunately,

00:02:45.550 the compiler doesn’t.

 

00:02:47.000 The compiler doesn't know that 15 Celsius

00:02:49.868 plus 50 Fahrenheit is 109 Fahrenheit,

00:02:52.327 so it silently gives the wrong answer.

00:02:55.195 The constraints the programmer knows about the

00:02:58.163 design are not represented in the types,

00:03:01.032 so the compiler can't catch the mistake.

 

00:03:05.000 To begin to address this problem,

00:03:07.527 we should define more specific types representing

00:03:10.476 temperatures in Celsius and in Fahrenheit,

00:03:13.003 and use those types, instead of integers

00:03:15.952 or floating point values throughout our program.

 

00:03:19.000 For example, if we look at the

00:03:21.198 main function at the bottom of the

00:03:23.396 sample on the slide, we let the

00:03:25.595 value C equal 15 Celsius and the

00:03:27.793 value F equals 50 Fahrenheit, and then

00:03:29.991 when we try to add them,

00:03:31.875 you get the error you see on

00:03:34.074 the left of the side. The code

00:03:36.272 doesn't compile.

 

00:03:37.000 It's expecting Celsius. It found Fahrenheit.

00:03:40.126 And t here's no conversion between them

00:03:43.774 defined. The compiler detects the bug.

 

00:03:47.000 How do we define these more specific

00:03:49.874 types?

00:03:51.034 They’re tuple structs, as shown at the

00:03:54.008 top of the listing.

 

00:03:55.000 They derive the PartialEq and PartialOrd traits,

00:03:57.819 from the standard library, that allow them

00:04:00.638 to be compared for equality and provide

00:04:03.457 ordering. And they derive the Debug trait,

00:04:06.276 that allows them to be printed by

00:04:09.095 debugging functions.

 

00:04:10.000 And, we see in the rest of

00:04:12.315 the code, we implement the addition function,

00:04:14.631 the Add trait from the standard library,

00:04:16.946 that allows us to add values in

00:04:19.262 Celsius together, or allows us to add

00:04:21.577 values in Fahrenheit together.

 

00:04:23.000 So if we have the types right,

00:04:25.709 if we're consistently using Celsius, or if

00:04:28.417 we're consistently using Fahrenheit, the addition will

00:04:31.126 work correctly.

 

00:04:32.000 However, in this case the code isn't

00:04:34.724 correct and the compiler catches our mistake.

00:04:37.448 Now this is obviously a simple example.

00:04:40.272 We’re only defining Celsius and Fahrenheit types,

00:04:42.996 and we only implement the addition operation,

00:04:45.720 and we only derive the partial equality

00:04:48.443 and partial ordering traits.

00:04:50.000 And of course in a real implementation

00:04:53.150 we’d also implement subtraction and multiplication and

00:04:56.300 division, and possibly a number of other

00:04:59.450 operations.

 

00:05:00.000 But it shows the principle.

00:05:02.227 We can begin to catch errors by

00:05:05.445 using specific numeric types in place of

00:05:08.564 the generic types.

 

00:05:10.000 There's some complexity here, of course.

00:05:12.137 We need to define tuple structs to

00:05:14.631 represent the Celsius and Fahrenheit types,

00:05:16.769 and we need to implement the various

00:05:19.262 traits for the operations we require.

 

00:05:21.500 There's more up-front design work, more up-front

00:05:24.790 implementation work, but we gain the ability

00:05:28.080 to check the designs for correctness.

 

00:05:31.000 For small programs this probably isn't a

00:05:33.691 win, but as the system gets more

00:05:36.382 complex, and as we include more information

00:05:39.073 about the constraints on the design in

00:05:41.764 types, we can catch more and more

00:05:44.456 bugs. It's very much a win overall

00:05:47.147 for large systems.

 

00:05:49.500 The type system in Rust is flexible

00:05:52.403 enough that we can add more features

00:05:55.307 to make use of these types more

00:05:58.210 natural. For example, we can add implementations

00:06:01.113 that perform unit conversions.

00:06:02.772 The standard library defines traits to represent

00:06:05.775 standard numerical operations, such as addition,

00:06:08.264 subtraction, multiplication and division, for example,

00:06:10.752 that are parameterised by the types on

00:06:13.656 which they operate.

 

00:06:15.000 In this example, we implement the Add

00:06:17.777 trait, with Fahrenheit as a type parameter,

00:06:20.553 for the Celsius type. This describes how

00:06:23.330 you add a Fahrenheit value to a

00:06:26.107 Celsius value.

 

00:06:27.000 And it allows the code in the

00:06:29.832 main() function to successfully add Celsius and

00:06:32.664 Fahrenheit values and print out the correct

00:06:35.495 result.

 

00:06:37.000 You should also think whether all the

00:06:39.635 standard operations makes sense for the numeric

00:06:42.271 types you define.

 

00:06:43.500 It's reasonable to compare temperature values for

00:06:46.259 equality, for example, or to compare two

00:06:49.018 temperatures to see which is the largest,

00:06:51.776 so you'd implement the standard equality and

00:06:54.535 ordinal traits that provide these operations.

 

00:06:57.000 It doesn't necessarily make sense to implement

00:06:59.297 such operations for all types, though.

00:07:01.267 If you have a UserID type,

00:07:03.336 you may want to implement the equality

00:07:05.633 trait to be able to check if

00:07:07.931 two UserID values are the same.

 

00:07:10.000 But adding two UserID values together,

00:07:12.968 or comparing UserID values to see which

00:07:16.432 is largest, may not be meaningful.

 

00:07:19.500 You don't necessarily need to implement all

00:07:21.937 the standard operations for the specific numeric

00:07:24.374 types you define. You just implement those

00:07:26.811 that makes sense for those types.

 

00:07:29.000 Not all numeric types are actually numbers,

00:07:31.473 and not all numeric types should be

00:07:33.947 treated as if they are numbers.

00:07:36.067 Some are merely identifiers, and you can

00:07:38.540 make sure that they're used in that

00:07:41.013 way, by disallowing operations that are not

00:07:43.487 meaningful for the data.

 

00:07:46.000 What's interesting is that wrapping numeric values

00:07:48.911 inside tuple structs in this way has

00:07:51.821 no runtime overhead in Rust.

 

00:07:54.000 There's clearly some programmer overhead.

00:07:56.000 The programmer needs to think about what

00:07:58.900 types exist, and what operations make sense

00:08:01.700 on those types. And needs to implement

00:08:04.500 the standard operations. So there's a bunch

00:08:07.300 of extra code that's needed. There’s more

00:08:10.100 up-front design work, more up-front implementation work.

 

00:08:13.000 And I don't want to downplay this.

00:08:15.310 It can be quite a lot of

00:08:17.620 work. You need to be implementing a

00:08:19.930 reasonably large system before it becomes worth

00:08:22.240 the effort.

 

00:08:23.000 I’ll note, though, that there are macros,

00:08:25.703 such as the newtype_derive crate mentioned on

00:08:28.406 the slide, that make this easier in

00:08:31.108 the common cases, and make it straightforward

00:08:33.811 to define the common operations with little

00:08:36.514 code.

 

00:08:37.000 This extra code – this extra implementation

00:08:40.355 effort – leads to no runtime change

00:08:43.710 in the generated code. The additional checking,

00:08:47.066 the additional functionality, exists purely at compile

00:08:50.421 time.

 

00:08:51.000 Why is there no runtime cost?

 

00:08:54.000 Well, in part because tuple structs add

00:08:56.771 no extra information compared to an integer,

00:08:59.543 or a floating point type. They hold

00:09:02.314 the same values, and so have the

00:09:05.086 same size. And since Rust doesn't automatically

00:09:07.857 box values, they’re passed around in exactly

00:09:10.629 the same way as the primitive types.

 

00:09:13.500 When generating code, the compiler and optimiser

00:09:16.048 recognise that the operations being performed are

00:09:18.596 equivalent to those on the primitive types,

00:09:21.144 and will generate the exact same code

00:09:23.692 to do so, as if they were

00:09:26.240 operating natively on those primitive types.

00:09:28.424 When adding Celsius and Fahrenheit values,

00:09:30.708 for example, as we saw in the

00:09:33.256 previous slides, the code that’s generated is

00:09:35.804 the exact same code as if we

00:09:38.352 were natively working with floating point values.

 

00:09:41.000 Wrapping the primitive type in a tuple

00:09:44.215 struct and implementing the various operations provides

00:09:47.430 compile-time checking for correctness, but doesn’t affect

00:09:50.644 the generated code in any way.

 

00:09:53.500 And this behaviour is not unique to

00:09:56.300 Rust. Equivalent C++ code has exactly the

00:09:59.100 same properties, for example, but there are

00:10:01.900 not many languages which allow you to

00:10:04.700 pass unboxed values around, and to have

00:10:07.500 precise control over the data layout.

 

00:10:10.000 The type system in Scala is expressive

00:10:12.628 enough to represent numeric types such as

00:10:15.255 these, and to perform the sorts of

00:10:17.883 checks I’ve described. But, because the resulting

00:10:20.510 code runs on the Java virtual machine,

00:10:23.138 it would have a lot more overhead.

00:10:25.765 In Rust or C++ you can wrap

00:10:28.393 a primitive type in a struct,

00:10:30.645 and do so with no runtime overhead.

00:10:33.272 That's not possible in many other languages.

 

00:10:37.000 Wrapping numeric types is an important design

00:10:40.450 pattern that's useful in Type Driven Design.

 

00:10:44.000 Another such a pattern that becomes useful

00:10:46.725 in Rust, is to use enum types

00:10:49.450 and pattern matching to model alternatives,

00:10:51.786 options, results, features and response codes,

00:10:54.121 and flags.

 

00:10:55.000 This lets the compiler check these types

00:10:57.888 for correctness, and further helps us debug

00:11:00.775 our design before we start running and

00:11:03.663 debugging our code.

 

00:11:06.000 Sometimes a program has to work with

00:11:08.596 values that might not be present.

00:11:10.821 We can use the Option type to

00:11:13.417 represent these in Rust.

 

00:11:15.000 For example, if a function might return

00:11:17.384 a value, or might not be able

00:11:19.769 to find that value, such as the

00:11:22.153 lookup() functions shown on the slide,

00:11:24.197 we return an optional result.

 

00:11:26.000 As we saw in the previous lecture,

00:11:28.508 this is safer than returning an optional

00:11:31.017 null pointer because the compiler forces us

00:11:33.525 to pattern match when using the value

00:11:36.033 and handle both the Some and None

00:11:38.542 cases.

 

00:11:39.000 It's also more semantically meaningful. It makes

00:11:42.647 the intent clearer in the program.

00:11:45.774 Essentially, it provides machine checkable documentation.

 

00:11:50.000 It's also possible to use optional values

00:11:52.718 as part of struct definitions.

00:11:54.659 For example, here we see the definition

00:11:57.476 of a network packet format, an RTP

00:12:00.194 header, as shown on the right.

00:12:02.524 This is represented in Rust code is

00:12:05.241 shown on the left, with the definition

00:12:07.959 of the struct RtpHeader type.

 

00:12:10.000 An RTP header contains an optional field,

00:12:12.665 known as the header extension.

00:12:14.568 We can represent this in the struct,

00:12:17.332 by including an Option type in the

00:12:19.997 struct definition representing that format.

 

00:12:22.000 Again, this makes the intent clear to

00:12:24.950 both the compiler and to other programmers.

 

00:12:29.000 In both cases, whether we use an

00:12:31.310 Option as a return value from a

00:12:33.620 function, or as a field in a

00:12:35.930 struct, the compiler enforces that both variants

00:12:38.240 are handled.

 

00:12:39.000 The compiler enforces that we check both

00:12:41.784 the Some case, where the value exists,

00:12:44.569 and the None case where the field

00:12:47.353 or the value isn't present. We can't

00:12:50.138 accidentally write code that assumes the value

00:12:52.922 is always present and crashes at run

00:12:55.707 time if not.

 

00:12:58.000 In addition to Option, Rust has a

00:13:01.019 Result type that represents a computation that

00:13:04.037 can fail.

 

00:13:05.000 For example, the slide shows a load_document()

00:13:07.430 function that returns a result that can

00:13:09.860 either be a Document object, or a

00:13:12.290 database error.

00:13:12.984 In the same way that the Option

00:13:15.514 type encode a better version of the

00:13:17.944 idiom of returning a null pointer on

00:13:20.374 failure, the result type is a better

00:13:22.804 version of exception handling or of functions

00:13:25.234 that return a sentinel value, such as

00:13:27.664 -1, to indicate an error.

 

00:13:29.500 And, in the same way that the

00:13:31.632 Option type forces us to pattern match

00:13:33.764 to extract the value, and make sure

00:13:35.895 we consider the case where the value

00:13:38.027 is absent, the Result type make sure

00:13:40.159 that we consider both the success and

00:13:42.291 failure conditions.

 

00:13:43.000 The only way to get at the

00:13:45.628 result value is by pattern matching.

00:13:47.881 We can either check the Ok() case

00:13:50.509 and retrieve the successful value, or we

00:13:53.138 can check the Err() case and retrieve

00:13:55.766 the failure value. It's not possible to

00:13:58.394 write code that doesn't perform the check

00:14:01.023 – such code won’t compile.

 

00:14:03.000 The Result type is the equivalent of

00:14:06.118 exception handling in Rust.

 

00:14:08.000 The difference from exceptions is that it's

00:14:10.465 more explicit.

00:14:11.170 Exceptions can be explicitly thrown at any

00:14:13.735 point in the code, but can also

00:14:16.200 be thrown by any method or function

00:14:18.665 that is called. In general, it’s not

00:14:21.130 possible to know if an operation will

00:14:23.596 throw an exception or not, except by

00:14:26.061 careful reading to the documentation. That a

00:14:28.526 function throws an exception is generally not

00:14:30.991 visible in the code.

 

00:14:32.500 Results, on the other hand, are explicitly

00:14:35.089 returned from functions. It’s always clear when

00:14:37.678 a Rust function can fail, because it

00:14:40.267 will have a Result type as its

00:14:42.856 return value.

00:14:43.595 As with the Option type, it’s necessary

00:14:46.284 to pattern match on Results to determine

00:14:48.873 if they encode success or failure,

00:14:51.092 and to extract the result value.

00:14:53.311 This forces code to handle both cases.

 

00:14:56.000 Rust has a shortcut, though, for propagating

00:15:00.288 errors.

 

00:15:01.000 If we look at the calls to

00:15:03.689 the open_database() and db.load() functions on the

00:15:06.377 slide, we’ll see that they end in

00:15:09.066 a question mark. These functions return a

00:15:11.755 Result type, and the annotation indicates that

00:15:14.443 this should potentially be propagated up the

00:15:17.132 call chain.

 

00:15:18.000 The compiler expands function or method calls

00:15:20.813 annotated in this way, adding the equivalent

00:15:23.627 of a match statement around them.

00:15:26.038 If the called function returns Ok(),

00:15:28.450 this simply extracts that value and continues.

00:15:31.263 But, if the called function returns an

00:15:34.077 error, then it executes a return statement

00:15:36.890 to propagate that error further.

 

00:15:39.000 For example, if the open_database() call returns

00:15:41.862 a result indicating an error, the annotation

00:15:44.724 on the call will cause the load_document()

00:15:47.585 function to return at that point,

00:15:50.038 passing the error up to its caller.

 

00:15:53.000 This has the same effect as throwing

00:15:55.271 an exception would, with the error working

00:15:57.543 its way up the call stack until

00:15:59.814 it either hits a match statement that

00:16:02.086 handles it, or until it reaches main(),

00:16:04.357 in which case the program is cleanly

00:16:06.629 aborted if the error is not handled.

 

00:16:10.000 The option and result types in Rust

00:16:12.489 are very useful, and help detect common

00:16:14.978 problems at compile time.

 

00:16:16.500 Enum types are also useful to encode

00:16:19.160 properties of the design that relate to

00:16:21.820 the problem domain. They can often be

00:16:24.480 used to help avoid common anti-patterns in

00:16:27.140 system design.

 

00:16:28.000 The first of these anti-patterns is known

00:16:30.927 as string typing.

00:16:32.182 String typing is where method parameters,

00:16:34.791 return types, and data values are coded

00:16:37.718 as unstructured strings, rather than as some

00:16:40.645 more appropriate type.

 

00:16:42.000 For example, it’s the case where strings

00:16:44.580 returned from some network operation, such as

00:16:47.160 HTTP response code, are used directly in

00:16:49.740 the rest of the program, rather than

00:16:52.320 being converted to some structured internal representation.

 

00:16:55.000 By using an enum, we can represent

00:16:57.813 data such as this, that can take

00:17:00.627 one of several possible values, in a

00:17:03.440 structured way. This has some overhead,

00:17:05.852 because we must define the enum that

00:17:08.665 represents the different states, and convert the

00:17:11.479 string representation into the internal format,

00:17:13.890 but provides some nice properties.

 

00:17:16.000 It enables exhaustiveness checking. We can be

00:17:18.317 sure our code handles all possible values.

00:17:20.633 And we can be sure the compiler

00:17:22.950 will catch any cases we miss,

00:17:24.936 if new values are introduced and the

00:17:27.252 code needs to be updated to handle

00:17:29.569 them.

 

00:17:30.000 We get ease of refactoring, since the

00:17:33.220 internal code is decoupled from the external

00:17:36.440 representation

 

00:17:37.000 And we make nonsensical values unrepresentable.

00:17:39.606 Only the values encoded into the enum

00:17:42.647 can be passed around internally, and invalid

00:17:45.688 values can’t leak into our program from

00:17:48.728 the rest of the system.

 

00:17:51.000 Essentially, the types provide a representation and

00:17:54.114 documentation that’s also meaningful to, and can

00:17:57.228 be checked by, the compiler, whereas the

00:18:00.341 string types are only meaningful to the

00:18:03.455 programmer.

 

00:18:05.000 The second anti-pattern is over-use of boolean

00:18:08.611 flags.

00:18:09.876 The use of boolean flags as arguments

00:18:13.587 to function obscures meaning.

 

00:18:15.000 Compare the two examples on the slide.

 

00:18:18.000 The first, calls file.open(), and passes in

00:18:21.253 a filename and two flags, one true

00:18:24.506 and one false.

 

00:18:26.000 What those flags mean is entirely hidden,

00:18:29.281 unless you’ve memorised the documentation for the

00:18:32.562 open() function.

 

00:18:33.600 The second variant performs the same operation,

00:18:36.383 but this time the arguments are encoded

00:18:39.166 as enums rather than booleans. The first

00:18:41.949 argument is an enum with values TextMode

00:18:44.732 and BinaryMode, and the second is an

00:18:47.515 enum with values ReadOnly and ReadWrite.

 

00:18:50.000 The underlying logic is the same,

00:18:52.400 but the types make the behaviour more

00:18:55.200 obvious. They’re easier for the programmer to

00:18:58.000 read.

 

00:18:58.500 And they allow the compiler to check

00:19:00.840 that the arguments are passed correctly.

00:19:02.846 In the first version of the code,

00:19:05.186 with the boolean arguments, if the programmer

00:19:07.526 swaps the arguments by accident, then the

00:19:09.866 code will compile fine, but fail at

00:19:12.206 runtime. In the version using enums,

00:19:14.211 the code is both more obvious,

00:19:16.217 and won’t compile if the arguments are

00:19:18.557 passed in the wrong order, because the

00:19:20.897 types won’t match.

 

00:19:22.000 The blog posts listed on the slide

00:19:24.450 talk about this idea in more detail.

 

00:19:28.000 The fundamental idea of type driven design

00:19:30.631 is to use the type system to

00:19:33.262 describe features of the system design,

00:19:35.517 so the compiler can help check them

00:19:38.148 for correctness.

 

00:19:39.000 There’s an up-front cost, of course.

00:19:41.450 You need to define the types.

 

00:19:44.000 The benefit is that fixing compilation errors

00:19:46.683 is easier than fixing silent data corruption,

00:19:49.367 when the program fails.

 

00:19:51.000 For small systems, the cost may outweigh

00:19:54.059 the benefit.

00:19:54.933 But, for large systems, compiler enforced consistency

00:19:58.093 checks due to use of types can

00:20:01.152 be a significant win.

 

00:20:04.000 This wraps up our discussion of design

00:20:07.090 patterns for type-driven design.

00:20:08.855 In the next part, I’ll move on

00:20:12.045 to discuss how state machines can be

00:20:15.134 cleanly represented and checked.

Part 3: State Machines

The 3rd part of the lecture discusses how state machines can be implemented. State machines are widely used in the implementation of device drivers and network protocols, so it's important to be able to express them cleanly in systems programs. The lecture reviews two ways of doing this, one implemented using enumerations, one using structure types, and discusses the trade-offs between them.

00:00:00.000 In this third part of the lecture,

00:00:03.213 I want to discuss state machines.

00:00:05.110 I’ll talk about what is a state

00:00:07.423 machine, and how state machines can be

00:00:09.635 cleanly implemented in Rust.

 

00:00:11.000 In particular, I’ll talk about two different

00:00:14.052 implementation strategies, one using enum types and

00:00:17.104 one using struct types, and the trade-offs

00:00:20.156 between the two approaches.

 

00:00:23.000 State machines are common in systems code.

00:00:25.740 They’re frequently used to represent the behaviour

00:00:28.579 of a network protocol, file systems,

00:00:30.928 device drivers, and so on.

00:00:32.884 They model the behaviour of the system

00:00:35.724 as a set of states reflecting the

00:00:38.464 status of the system, transitions between those

00:00:41.203 states triggered by events, and state variables

00:00:43.943 that hold the system configuration.

 

00:00:46.000 The figure shows an example of this,

00:00:48.881 where the system moves between different states,

00:00:51.762 the yellow boxes, in response to events.

00:00:54.643 Some of those events may be triggered

00:00:57.525 by programmer actions, while others are in

00:01:00.406 response to external events and actions.

00:01:02.875 We see that the system can move

00:01:05.757 through the states to eventually reach to

00:01:08.638 IO_RUNNING state, or can be reconfigured at

00:01:11.519 various points, returning to the IO_CONFIGURE_BEGIN state.

 

00:01:14.500 The example represents a network device driver,

00:01:17.459 and the details of what it’s doing

00:01:20.418 aren’t important.

00:01:21.264 What matters, though, is the pattern.

 

00:01:24.000 We see state machines in many systems.

00:01:26.800 To represent the behaviour of an Ethernet

00:01:29.700 driver, as in the example, or a

00:01:32.500 WiFi interface. To represent the TCP connection

00:01:35.300 establishment handshake. Or the state of a

00:01:38.100 file system, or a disk driver,

00:01:40.500 or some other piece of hardware.

 

00:01:43.000 And it’s often useful to formalise the

00:01:45.731 code, and explicitly write down the state

00:01:48.462 machine, with its various events and transitions,

00:01:51.193 and use this to drive the implementation.

00:01:53.924 The state machine captures the essence of

00:01:56.755 the systems behaviour. It captures the high-level

00:01:59.486 structure of the design.

00:02:01.046 And it should be easy to reason

00:02:03.877 about. To prove properties such as termination,

00:02:06.608 absence of deadlocks, whether all states are

00:02:09.339 reachable, and so on.

 

00:02:12.000 That said, it can be difficult to

00:02:14.553 cleanly implement state machines in code.

00:02:16.741 The structure of the code often tends

00:02:19.394 not to match the structure of the

00:02:21.947 state machine, and it’s often not easy

00:02:24.500 to understand what state the system is

00:02:27.053 in, or to visualise the transitions.

00:02:29.241 This information is often encoded in mutable

00:02:31.794 state variables, hidden in a mass of

00:02:34.347 conditional operations, and spread throughout the code.

 

00:02:37.000 This makes it difficult to validate the

00:02:39.949 code against the specification. It makes it

00:02:42.898 difficult to check the state machine.

00:02:45.426 Recently, though, we’ve started to see new

00:02:48.475 approaches to modelling state machines in strongly-typed

00:02:51.425 functional languages. These make the code clearer,

00:02:54.374 and make the state machine more obvious.

00:02:57.323 They encode states and events as enumerations,

00:03:00.372 and pattern match on state-event tuples.

 

00:03:03.000 Or they encode states as types,

00:03:05.450 and transitions as functions.

00:03:07.083 Or they add first-class state machine support

00:03:10.042 to the language and to its runtime.

 

00:03:13.000 This latter is shown on the right,

00:03:15.426 and is a code fragment taken from

00:03:17.851 a paper about the Singularity operating system

00:03:20.277 from Microsoft Research. It’s also the approach

00:03:22.702 taken by asynchronous code, often used for

00:03:25.128 concurrency, that we’ll talk about in Lecture

00:03:27.553 8.

 

00:03:28.000 I’ll talk about other two approaches in

00:03:30.753 the remainder of this part of the

00:03:33.507 lecture.

 

00:03:35.000 There are two possible state machine implementation

00:03:37.898 strategies that leverage these insights and can

00:03:40.795 be used in Rust.

00:03:42.451 The first is to use enumerated types,

00:03:45.449 enums, to represent the states and the

00:03:48.347 events and to use functions to represent

00:03:51.244 state transitions and actions.

 

00:03:53.000 In this approach you define one enum

00:03:55.673 type to represent all the possible states,

00:03:58.345 and another to represent all the possible

00:04:01.018 events.

 

00:04:01.500 You define a function that takes a

00:04:04.300 tuple of state and event, and returns

00:04:07.100 the next state, encoding the state transitions.

 

00:04:10.000 And you define a function to represent

00:04:12.887 the action performed on each transition.

00:04:15.362 This approach builds on the intuition that

00:04:18.350 enum types express alternatives.

00:04:20.000 And the idea that a state machine

00:04:22.304 is a set of alternative states with

00:04:24.608 transitions between those states driven a set

00:04:26.913 of possible events.

 

00:04:29.000 You start by defining the enums that

00:04:32.139 represent the states and the events.

00:04:34.830 In this example, the enum representing the

00:04:38.070 states is enum ApcState, and that representing

00:04:41.209 the events is the ApcEvent enum.

 

00:04:44.000 What the system is modelling isn’t really

00:04:46.686 important, but we see from ApcState that

00:04:49.373 it involves connections, TcpStream objects, and messages

00:04:52.059 that can be send and received on

00:04:54.746 those connections. It’s a network protocol of

00:04:57.432 some sort.

 

00:04:58.300 And we see that the system has

00:05:01.397 a typical set of states for a

00:05:04.494 networked system. It can be initialised,

00:05:07.148 waiting for connections, accepting connections, receiving messages,

00:05:10.245 closing a connection, and so on.

 

00:05:13.000 Similarly, in the ApcEvent enum, we see

00:05:16.161 a typical set of events for a

00:05:19.321 networked system. A TCP connection has connected.

00:05:22.482 A message has been received. Some response

00:05:25.642 is valid. And so on.

 

00:05:28.000 Both the states and the events are

00:05:31.150 encoded as enums, with parameters to those

00:05:34.300 enums holding state variables that provide additional

00:05:37.450 context.

 

00:05:39.000 Having defines the enums representing the states

00:05:42.116 and events, you define a function that

00:05:45.232 maps between states.

00:05:46.568 In the example, this function is a

00:05:49.784 method, next(), implemented on the ApcState enum.

 

00:05:53.000 Its parameters are self, an instance of

00:05:55.898 an ApcState enum representing current state,

00:05:58.381 and an instance of an ApcEvent object.

00:06:01.279 The function pattern matches on the tuple

00:06:04.277 of self, the current state, and the

00:06:07.174 event that occurred, and returns a new

00:06:10.072 ApcState instance.

 

00:06:11.000 We see that the body of the

00:06:13.514 function is a table, matching the (state,

00:06:16.027 event) tuples, that directly encodes the state

00:06:18.541 transitions.

 

00:06:19.000 The tuple of state and event is

00:06:21.157 matched against a list of states the

00:06:23.315 system can be in, and the events

00:06:25.472 that can occur in those states,

00:06:27.321 and evaluates to a new instance of

00:06:29.479 an ApcState object, that’s returned by the

00:06:31.636 function.

00:06:32.694 In there’s no match, the catch-all at

00:06:34.952 the end of the match statement is

00:06:37.109 taken, and the system fails.

 

00:06:38.000 This gives a very clean representation of

00:06:40.841 the state-transition table, that’s easy to validate

00:06:43.682 against the specification.

 

00:06:45.000 Importantly, the next() function takes ownership of

00:06:48.197 self. That is, the parameter is self

00:06:51.395 rather than &self. As we’ll see later,

00:06:54.592 this means it consumes the state,

00:06:57.332 and returns the new state, enforcing that

00:07:00.530 the transition occurs.

 

00:07:03.000 The enums representing the states and events,

00:07:05.923 and the state transition function that maps

00:07:08.846 between the states, are brought together in

00:07:11.768 a new struct representing the state machine

00:07:14.691 itself.

00:07:15.859 In this example, the ApcStateMachine struct holds

00:07:18.882 the current state and any extra data

00:07:21.804 needed for the system to operate.

00:07:24.310 In this case, a SocketAddr and a

00:07:27.232 timeout.

 

00:07:27.000 The state machine defines two functions.

 

00:07:30.000 The new() function creates an instance of

00:07:32.950 the state machine, in the initial state.

 

00:07:36.000 The run_once() function performs the actions for

00:07:38.760 the current state. It matches on the

00:07:41.521 value of the current state, and any

00:07:44.281 state variables encoded into that enum variant,

00:07:47.042 and performs whatever processing is needed.

00:07:49.408 When something happens that could potentially cause

00:07:52.168 the state to change, it returns an

00:07:54.928 event that describes what happened.

 

00:07:57.000 The run_state_machine() function we see on the

00:08:00.053 right shows how the state machine is

00:08:03.106 used.

00:08:04.292 It instantiates the ApcStateMachine object, and then

00:08:07.444 loops.

00:08:08.631 For each loop, it calls the run_once()

00:08:11.783 method, to retrieve the next event.

 

00:08:13.000 Then it calls the next() function on

00:08:15.514 the state, retrieving the next state and

00:08:18.027 storing it into the state machine struct.

00:08:20.541 If the system has entered the Finish

00:08:23.155 state, it breaks out of the loop.

00:08:25.668 Otherwise, it loops around and processes the

00:08:28.182 next event.

 

00:08:29.000 The logic needed to control the transition

00:08:31.333 between states is in the parameters of

00:08:33.667 the enums representing the states and events.

00:08:36.000 And the operations performed in each state

00:08:38.765 are written in the branches of the

00:08:41.530 match statement in the run_once() function.

 

00:08:44.000 This cleanly separates the actions to be

00:08:46.542 performed in each state, from the code

00:08:49.084 that manages the state transitions.

 

00:08:51.000 And it cleanly encodes the state transition

00:08:54.092 logic into a single function.

00:08:56.300 It’s a very elegant, easy to check,

00:08:59.492 way of representing state machines.

 

00:09:03.000 Rust also permits an alternative way to

00:09:05.950 model state machines, based around structure types.

00:09:08.900 In this alternative, each state is represented

00:09:11.950 by a struct. One struct per state.

00:09:14.900 Events are represented by method calls on

00:09:17.950 those structs.

00:09:18.793 And state transitions are modelled by returning

00:09:21.843 a struct that represents the new state.

00:09:24.793 This approach builds on the intuition that

00:09:27.843 states hold concrete state, and events are

00:09:30.793 things that happen in states.

 

00:09:34.000 The code fragments on this slide show

00:09:36.429 an example of the struct-based approach to

00:09:38.859 modelling state machines.

 

00:09:40.000 There are three possible states this system

00:09:43.600 can be in. It can be an

00:09:47.200 Unauthenticated Connection, an Authenticated Connection, or NotConnected.

00:09:50.800 Each is represented by a struct type.

 

00:09:54.500 A number of methods are implemented on

00:09:57.349 these structs, and the slide shows some

00:10:00.197 of those for the UnauthenticatedConnection struct.

00:10:02.639 We see that the login() method takes

00:10:05.588 the struct as its self parameter,

00:10:08.029 along with some credentials, and attempts to

00:10:10.878 login. If it succeeds, the Result it

00:10:13.726 returns includes an AuthenticatedConnection object, representing the

00:10:16.575 new state. If the login fails,

00:10:19.017 it returns a tuple comprising the current

00:10:21.865 state and the error message.

 

00:10:24.000 Similarly, the disconnect() method takes self as

00:10:26.712 its parameter, and returns a NotConnected struct

00:10:29.425 representing the system in the disconnected state.

00:10:32.137 Each call returns the new state the

00:10:34.950 system is in.

00:10:36.112 And, due to Rust’s ownership rules,

00:10:38.538 that we’ll discuss in the final part

00:10:41.250 of this lecture, it consumes the old

00:10:43.962 state, enforcing the state transition.

 

00:10:47.000 Which approach to representing a state machine

00:10:49.975 is best?

00:10:50.825 It depends on your priorities, of course.

 

00:10:54.000 The enum-based approach is compact, makes states

00:10:56.756 and events clear in the types,

00:10:59.119 and has a clear state transition table.

00:11:01.875 It’s good if the state machine is

00:11:04.631 complex, with many different states and transitions,

00:11:07.388 making it important to be able to

00:11:10.144 easily inspect the state-transition table for correctness.

 

00:11:13.000 It also relies on a language that

00:11:15.957 has expressive enum type, to allow its

00:11:18.915 implementation. This approach works well in Rust,

00:11:21.872 Swift, or OCaml, for example, but it’s

00:11:24.830 difficult to express in languages with weaker

00:11:27.787 enum types and pattern matching.

 

00:11:30.000 The struct-based approach encodes states and state

00:11:32.433 transitions in the types, and events as

00:11:34.867 methods on those types. The state transition

00:11:37.300 table is less obviously explicit in the

00:11:39.733 code, since it’s encoded in the return

00:11:42.167 types of methods, but when implemented in

00:11:44.600 Rust the ownership rules cleanly enforce the

00:11:47.033 transitions and ensure nothing from the previous

00:11:49.467 state is accessible in the new state.

 

00:11:52.000 Both approaches work well.

 

00:11:57.000 This concludes our discussion of state machines

00:11:59.224 in Rust.

00:11:59.860 I’ve briefly described what is a state

00:12:02.184 machine, and shown two different ways in

00:12:04.408 which state machines can be implemented,

00:12:06.315 using enums and using structs.

00:12:07.903 In the next part, I’ll move on

00:12:10.227 to discuss the ownership rules enforced by

00:12:12.452 Rust, that provide much of the power

00:12:14.676 of the struct-based approach to state machines.

Part 4: Ownership

The final part of the lecture discusses ownership. It reviews the features of the Rust programming language that allow it to track ownership of data, and how these relate to the design of reference types in Rust. Them, building on the material in the third part of the lecture, it shows how ownership types can be used to improve the implementation of state machines.

00:00:00.000 In this final part of the lecture,

00:00:03.185 I want to discuss one of the

00:00:05.371 more unusual features of Rust: its ownership

00:00:07.556 system.

00:00:08.618 I’ll discuss how Rust tracks ownership of

00:00:10.904 values, and the implications of this for

00:00:13.089 the way code is structured.

 

00:00:14.000 And I’ll talk about how the ownership

00:00:16.287 rules can be used to enforce state

00:00:18.573 transitions.

 

00:00:20.000 Systems programs care about ownership of resources.

00:00:22.638 In part this is important when implementing

00:00:25.377 state machines, as we discussed in the

00:00:28.015 previous part of this lecture.

 

00:00:30.000 It’s also important for managing memory,

00:00:32.725 and for managing resources such as files,

00:00:35.904 sockets, locks, and so on, as we’ll

00:00:39.083 discuss in Lecture 5.

 

00:00:41.000 When managing resources, such as memory,

00:00:43.227 a programmer will maintain some mental model

00:00:45.825 of what parts of the code own

00:00:48.423 each resource.

00:00:49.165 In languages like C, for example,

00:00:51.492 with manual memory management, the programmer needs

00:00:54.090 to keep track of what functions call

00:00:56.688 malloc() to allocate memory, and where that

00:00:59.287 memory is freed().

 

00:01:00.500 For every C function that takes a

00:01:02.600 pointer as an argument, the programmer has

00:01:04.700 to know whether that function will free

00:01:06.800 the memory, or whether it will leave

00:01:08.900 it for some other function to free.

00:01:11.000 Similarly, every C function that returns a

00:01:13.200 pointer has to make it clear whether

00:01:15.300 that pointer is owned by the library

00:01:17.400 returning it, and will be freed be

00:01:19.500 a later call to one of the

00:01:21.600 library functions, or whether it must be

00:01:23.700 freed by the caller.

 

00:01:25.000 If the programmer has the wrong understanding,

00:01:27.656 either the program forgets to free memory,

00:01:30.312 leading to a memory leak, or it

00:01:32.968 frees the memory too early, leading to

00:01:35.624 undefined behaviour and a segmentation fault.

 

00:01:38.000 Similar issues exist around management of other

00:01:41.085 resources, such as file descriptors and sockets.

00:01:44.170 It has to be clear who’s responsible

00:01:47.256 for closing the file or connection.

 

00:01:50.000 Different languages try to address the problem

00:01:53.177 of resource ownership in different ways.

 

00:01:56.000 Some languages, such as Java, use a

00:01:58.760 garbage collector to manage resources. This prevents

00:02:01.521 resources from being freed too early,

00:02:03.887 but still requires the programmer to understand

00:02:06.647 data ownership to know when to release

00:02:09.408 a reference to an object. This can

00:02:12.168 lead to memory leaks in Java programs,

00:02:14.928 if done incorrectly, for example.

 

00:02:17.000 Other languages, such as C++ and Python,

00:02:20.000 simplify resource management by linking resource lifetime

00:02:23.000 to program scoping rules. For example,

00:02:25.571 the code on the slide shows a

00:02:28.571 Python with statement, that opens a file

00:02:31.571 and assigns it to a variable that

00:02:34.571 lives for the duration of the with

00:02:37.571 statement.

 

00:02:38.000 When the variable goes out of scope,

00:02:39.820 the destructor for the object close the

00:02:41.640 file.

 

00:02:42.000 This is a powerful approach, and gives

00:02:45.456 automatic resource clean-up at the end of

00:02:48.913 the scope.

 

00:02:51.000 Rust takes a different, and more comprehensive,

00:02:53.923 approach to managing resources.

00:02:55.593 The Rust compiler and type system tracks

00:02:58.615 ownership of all data in a program.

00:03:01.538 It enforces that every value in the

00:03:04.560 program has a single owner at all

00:03:07.483 times.

 

00:03:08.000 To do this, Rust’s type system defines

00:03:11.290 rules about the transfer of ownership of

00:03:14.580 data in function and method calls.

 

00:03:17.500 There are three cases.

 

00:03:20.000 In the first case, a function that’s

00:03:22.567 passed a parameter by value will take

00:03:25.133 ownership of that value. We see this

00:03:27.700 in the consume() function on the slide,

00:03:30.267 that’s passed a resource, r, as its

00:03:32.833 parameter, and takes ownership of that resource.

 

00:03:35.500 The resource is no longer accessible to

00:03:38.950 the caller once the consume() function has

00:03:42.400 been invoked, and is freed once the

00:03:45.850 function completes.

00:03:46.836 The function consumes the resource.

 

00:03:49.500 In the second case, a function is

00:03:52.012 passed a parameter by reference. This is

00:03:54.524 known as borrowing a value. When a

00:03:57.035 parameter is borrowed in this way,

00:03:59.188 ownership of the resource remains with the

00:04:01.700 caller. The function can use the resource

00:04:04.212 it’s borrowed for the duration of the

00:04:06.724 call, but no longer. And when the

00:04:09.235 function returns, the caller still has access

00:04:11.747 to, and ownership of, the resource.

 

00:04:14.000 This means that a method on a

00:04:16.420 struct that borrows a resource can’t store

00:04:18.839 a reference to that resource in the

00:04:21.259 struct, for access once the function returns.

00:04:23.678 If you want to keep a reference

00:04:26.098 to a resource, you must consume it

00:04:28.517 rather than borrowing it.

 

00:04:30.000 The borrow() example function on the slide

00:04:32.930 takes an immutable reference to the resource,

00:04:35.860 that allows it to read the resource

00:04:38.791 but not modify it. Borrowing also works

00:04:41.721 with mutable references, written &mut, provided the

00:04:44.651 constraints on references discussed in Lecture 3

00:04:47.581 hold.

 

00:04:49.500 The final case is that a function

00:04:51.902 can return ownership of a value.

00:04:53.961 In this case, the function gives the

00:04:56.363 resource to its caller, making the caller

00:04:58.765 responsible for freeing that resource. The function

00:05:01.167 or method cannot retain any references to

00:05:03.569 the resource when it gives up ownership

00:05:05.971 in this way.

 

00:05:10.000 This code sample show the key features

00:05:12.482 of ownership in Rust.

 

00:05:14.000 The function main() creates a resource,

00:05:16.370 and stores it in a local variable,

00:05:19.135 r.

00:05:20.280 It then passes that resource to the

00:05:23.145 consume() function, that takes ownership of the

00:05:25.910 resource. That is, it passes the resource

00:05:28.675 by value to the function.

 

00:05:30.000 The main() function then tries to print

00:05:32.450 the value of the resource, r.

00:05:34.550 If you try to compile and run

00:05:37.100 this code, you’ll find that it doesn’t

00:05:39.550 compile.

 

00:05:40.000 The consume() function takes ownership of the

00:05:42.935 resource, and doesn’t pass it back to

00:05:45.869 the caller. Accordingly, when the consume() function

00:05:48.804 returns, the resource is deallocated.

 

00:05:51.000 Since it gave ownership of the resource

00:05:53.633 to the consume() function, the main() function

00:05:56.267 has no access to that resource thereafter.

 

00:05:59.000 The println!() call therefore fails: main() gave

00:06:01.656 away the resource and doesn’t have access

00:06:04.311 anymore, so it can’t print it.

00:06:06.587 If the main() function called the borrow()

00:06:09.343 function, as defined on the previous slide,

00:06:11.998 instead of consume(), then the code would

00:06:14.654 compile and run. A function that borrows

00:06:17.310 its argument gives it back when it

00:06:19.965 concludes. One that consumes its argument does

00:06:22.621 not.

 

00:06:26.000 As we saw in the previous part

00:06:28.613 of this lecture, state machines manage resources.

00:06:31.227 A state machine representing a network protocol

00:06:33.940 manages connections and the data sent over

00:06:36.553 them. A state machine representing a device

00:06:39.167 driver manages the hardware of the device.

00:06:41.780 And so on.

 

00:06:43.000 State transitions indicates changes to resource ownership.

00:06:45.735 They indicate that some event has occurred,

00:06:48.570 and that the system must move to

00:06:51.305 a new state, potentially consuming or releasing

00:06:54.040 resources held by the old state,

00:06:56.384 or keeping them for use by the

00:06:59.119 new state.

 

00:07:00.000 This is a natural fit for the

00:07:03.118 ownership rules in Rust.

 

00:07:06.000 If we think back to the struct-based

00:07:08.380 approach to writing state machines, that we

00:07:10.760 saw in the previous part of this

00:07:13.140 lecture, we see that it uses Rust’s

00:07:15.520 ownership rules to enforce clean state transitions.

 

00:07:18.000 In this approach, each state is represented

00:07:21.046 by a struct, and state transitions are

00:07:24.091 represented by methods implemented on that struct.

00:07:27.137 Importantly, those methods take ownership of the

00:07:30.282 struct. That is, they consume the state

00:07:33.328 they’re transitioning away from, ensuring there are

00:07:36.374 no more references to that state and

00:07:39.419 any resources they don’t explicitly return are

00:07:42.465 freed.

 

00:07:43.000 The transition methods then return ownership of

00:07:45.665 a value representing the new state,

00:07:47.950 populated with any values that need to

00:07:50.615 be retained from the previous state.

 

00:07:53.000 For example, the login() method of the

00:07:56.792 UnauthenticatedConnection struct consumes the struct, and creates

00:08:00.583 and returns ownership of a new AuthenticatedConnection

00:08:04.375 struct on success.

00:08:06.000 The login() method explicitly copies any data

00:08:09.052 that needs to be retained to the

00:08:12.104 new struct it returns; state that isn’t

00:08:15.156 copied over is released.

 

00:08:17.000 If the login() method fails, it returns

00:08:19.423 a tuple comprising an error and the

00:08:21.846 value of self. That is, after taking

00:08:24.269 taken ownership of self, it passes it

00:08:26.692 back to the caller when a failure

00:08:29.115 occurs. This keeps the object alive if

00:08:31.538 something goes wrong: the old state becomes

00:08:33.962 the new state.

 

00:08:36.500 This, then, is the advantage of the

00:08:39.628 struct-based approach to state machines.

00:08:41.862 It uses Rust’s ownership rules to enforce

00:08:45.091 state transitions, and to guarantee that resources

00:08:48.219 and cleaned-up when state transitions occurs.

 

00:08:51.000 The struct-based approach to managing state machines

00:08:53.695 is good for ensuring that all resources

00:08:56.390 are cleaned-up after use. It’s better if

00:08:59.085 your state machine manages a complex set

00:09:01.780 of resources, where the set of resources

00:09:04.475 used in each state differs.

 

00:09:06.500 The enum-based approach to state machines makes

00:09:09.391 the state transition diagram clearer, but relies

00:09:12.283 more on programmer discipline to manage and

00:09:15.174 clean-up resources.

 

00:09:19.000 Type-driven development is an approach to structuring

00:09:21.709 the development process that emphasises use of

00:09:24.417 the type system to ensure the design

00:09:27.126 is correct.

 

00:09:28.000 It allows you to incrementally debug the

00:09:30.935 design, and as the code develops also

00:09:33.869 the implementation, using the compiler as a

00:09:36.804 model checker to ensure consistency.

 

00:09:39.000 In type-driven design, you proceed by defining

00:09:41.753 the types first.

00:09:42.933 You define specific numeric types to represent

00:09:45.787 the different sorts of numeric values and

00:09:48.540 identifiers your code will work with.

 

00:09:51.000 You define enum types to represent alternates,

00:09:54.220 and to indicate optional values, results,

00:09:56.980 and errors

 

00:09:59.000 Using the types as a guide,

00:10:01.212 you write the function

00:10:02.688 Write the input and output types –

00:10:05.369 the function prototypes – and run the

00:10:07.950 compiler to check the design for consistency.

00:10:10.531 When, gradually implement the functions, piece by

00:10:13.212 piece, using the structure of the types

00:10:15.794 as a guide.

 

00:10:17.000 Make the state machine explicit.

00:10:18.655 And think about ownership of the data,

00:10:21.071 and how it’s passed between function and

00:10:23.388 around in state machines. The Rust ownership

00:10:25.705 rules, and the compiler, will help you

00:10:28.021 check that this is being done correctly

00:10:30.338 and consistently.

 

00:10:35.000 Refine and edit the types and functions

00:10:37.267 as necessary.

00:10:37.914 Use the compiler as a tool to

00:10:40.281 help you debug your design.

 

00:10:43.000 Importantly, don’t think of the types as

00:10:45.800 checking the code, think of them as

00:10:48.600 a plan, a model, for the solution

00:10:51.400 – as machine checkable documentation.

 

00:10:53.500 Use the compiler as a tool to

00:10:56.487 debug your design, before you run your

00:10:59.473 code.

 

00:11:01.000 This concludes our tour of type-driven development

00:11:03.638 in Rust.

00:11:04.392 In the next lecture, we’ll move on

00:11:07.131 to discuss resource ownership and memory management

00:11:09.769 in more detail.

Discussion

The lecture focussed on type-based modelling and design. It discussed the concept of using the types to help structure and organise the design of a system, and model the problem space, and using the compiler to help check the design for correctness.

The idea is to use types to check the design, debugging before you run the code. Nonsensical operations shouldn't cause a crash – they shouldn't compile. It's a change of perspective: the compiler is a model checking tool that can help validate your design.

The lecture also suggested some concrete ways in which the type system can help in this modelling: numeric types, options and results, feature flags, avoiding string typing, and modelling state machines.

From what you have seen so far, does this approach make sense? At what point do the benefits of modelling the system and developing the types outweigh the costs of doing so?