Home / Learn / 2 Numbers

Release v0.4.0Edition 0.2

2.3 Fixed-width integers

Page 4 of 9

2.3.1 What a fixed-width integer is

An Int grows as large as it needs. A fixed-width integer has a set number of bits, and so a smallest and a largest value. Think of the counter on a parking ticket machine with three digits: it shows 0 to 999, and nothing past that. A computer stores such a number in 8, 16, 32 or 64 bits, and other programs, file formats and devices often expect exactly that: a byte, 8 bits, holds 0 to 255.

Una has the unsigned types U8, U16, U32 and U64, which hold 0 and up, and the signed types I8, I16, I32 and I64, which hold negative values too. The number is the width in bits:

Type Smallest Largest
U8 0 255
U16 0 65535
U32 0 4294967295
U64 0 18446744073709551615
I8 -128 127
I16 -32768 32767
I32 -2147483648 2147483647
I64 -9223372036854775808 9223372036854775807

Each is its own type, distinct from Int and from the others.

Note

The fixed-width types belong to edition 0.2 and later, the edition of every package in this book. In a package of edition 0.1, U8 and the others are ordinary names.

2.3.2 Why every operation is proved

In many languages a fixed-width number that passes its largest value wraps around: 255 + 1 in a byte gives 0, with no error. A count of 256 labels kept in a byte becomes 0, the label printer prints nothing, and nobody knows why. In Una a fixed-width value never wraps around unless the code asks for it by name. Every +, -, *, /, mod and minus sign on one is a proof obligation: the verifier must prove that the exact result fits the type.

A function that adds 1 to a byte, with nothing to say the byte is below 255, does not check:

steps/16-overflow/src/printer.unauna
--- How many copies of a label to print: one per facing on the shelf, and one spare.
--- The label printer reads the count as one byte, so it is a `U8`.
pub copies(facings: U8) -> U8 = facings + 1
Diagnostic
[U5001] Error: overflow obligation `facings + 1 in 0..255` is refuted
   │ Help 1: repair 1: guard the operation with `if facings.to_int() + 1 in 0..255`
   │ Help 2: repair 2: give the values a wider type, converting them explicitly
   │ Help 3: repair 3: if wrapping or saturating is meant, use `wrapping_add`, `saturating_add` or their siblings
   │ Note 2: counterexample: facings = 255

The obligation facings + 1 in 0..255 says that the sum must lie between 0 and 255, and the counterexample is the one value that breaks it, 255. The three repairs are the three honest choices: test the range first, with an if (section 3.4), use a wider type, or say that wrapping or stopping at the end of the range is what you mean. Each makes the behavior at the edge of the range visible in the code.

2.3.3 How to write fixed-width values

2.3.3.1 A literal takes the type its place expects

let copies: U8 = 200 makes 200 a U8, since the name's type says so. A literal also takes the type of the parameter it is passed to, or of the other operand of an operator. A literal that does not fit its type does not check, as How fixed-width integers behave shows.

2.3.3.2 Method calls

The operations of this section are methods: functions written after a value, with a dot. copies.to_int() calls to_int on copies, as @console.print(…) calls print on the console. A method call always takes its parentheses here, and a second value goes in them with its label, as in copies.wrapping_add(by: 100). Section 3.2 covers method calls in full.

2.3.3.3 Converting between integer types

2.3.3.4 Wrapping and saturating, by name

These never leave the range, so they need no proof.

2.3.4 Each form at work

The step writes each form:

steps/17-widths/src/widths.unauna
module widths

--- Prints values of fixed-width types, and what their methods give.
pub main() -> Unit
  uses @console: Console[print]
=
  let copies: U8 = 200
  let offset: I8 = -128
  let largest: U64 = 18_446_744_073_709_551_615
  @console.print("{copies}, {offset} and {largest}")
  @console.print("{copies.to_int() + 100} as an Int")
  @console.print("{copies.wrapping_add(by: 100)} wrapped, {copies.saturating_add(by: 100)} saturated")
  let count = 42
  @console.print("{count.to_u8()} as a U8")
Output
200, -128 and 18446744073709551615
300 as an Int
44 wrapped, 255 saturated
42 as a U8

copies.to_int() + 100 is an Int, so 300 is fine. In a U8, 200 + 100 wraps around to 44, since 300 − 256 is 44, or saturates at 255. count.to_u8() narrows the Int 42: the verifier knows that count is 42, so it proves that it fits.

2.3.5 Label copies as one byte: U8

The module printer counts the copies of a shelf label in a U8, and a roll of labels in a U16:

steps/15-printer/src/printer.unacheckrununa
module printer

--- How many copies of a label to print: one per facing on the shelf, and one spare.
--- The label printer reads the count as one byte, so it is a `U8`.
pub copies(facings: U8) -> U8
  requires facings < 255
=
  facings + 1

--- Prints how many labels two shelves need.
pub main() -> Unit
  uses @console: Console[print]
=
  let lamps: U8 = 4
  let mugs: U8 = 12
  let lamp_labels = copies(lamps)
  let mug_labels = copies(mugs)
  @console.print("{lamp_labels} and {mug_labels} labels")
  let labels = lamp_labels.to_int() + mug_labels.to_int()
  @console.print("{labels} labels in all")
  let roll: U16 = 1_000
  @console.print("{roll.saturating_sub(by: 1_200)} left on a roll of {roll} after 1200")
  1. pub copies(facings: U8) -> U8. The label printer reads the number of copies as one byte, so the result is a U8. A facing is one row of a product on the front of a shelf.
  2. requires facings < 255. A precondition: a rule every caller must meet, written on its own line under the header, before =. Here it says that facings is less than 255, so that facings + 1 fits in a U8. The verifier proves the addition from it, and checks the rule at each call. Chapter 5 covers preconditions in full.
  3. let lamps: U8 = 4. A literal takes the type its place expects, here U8.
  4. lamp_labels.to_int() + mug_labels.to_int(). Two U8 values turned into Int before they are added. The sum is an Int, and cannot overflow.
  5. roll.saturating_sub(by: 1_200). Subtraction that stops at the bottom of the range, 0, instead of going below it.

una run . prints:

Output
5 and 13 labels
18 labels in all
0 left on a roll of 1000 after 1200

2.3.6 How fixed-width integers behave

2.3.6.1 A literal must fit at once

A literal that does not fit its type is refused before any proof. Write 300 for the U8 of widths:

Diagnostic
[U2022] Error: the literal `300` does not fit `U8`, which holds `0` to `255`
   ╭─[ src/widths.una:7:20 ]
   │
 7 │   let copies: U8 = 300
   │                    ─┬─
   │                     ╰─── the literal `300` does not fit `U8`, which holds `0` to `255`

The message gives the range of the type, so you can see why: a U8 holds 0 to 255. A minus sign with its literal counts as one literal, so -128 fits an I8.

2.3.6.2 Types do not mix

An operation takes two values of one type. Add the Int count to the U8 copies:

Diagnostic
[U2001] Error: an operand of `+` must be `U8`, found `Int`
    ╭─[ src/widths.una:14:29 ]
    │
 14 │   @console.print("{copies + count} in all")
    │                             ──┬──
    │                               ╰──── an operand of `+` must be `U8`, found `Int`

The U8 came first, so the message asks the other operand to be a U8 too. Convert one of them: copies.to_int() + count is an Int sum.

2.3.6.3 A narrowing must be proved

A conversion that may not fit is proved like an operation. A function that narrows any Int to a U8 does not check:

steps/20-narrowing/src/tags.unauna
--- The number of copies, as the label printer reads it: one byte.
pub copies_byte(copies: Int) -> U8 = copies.to_u8()
Diagnostic
[U5001] Error: overflow obligation `copies.to_u8() in 0..255` is refuted
   │ Help 1: repair 1: guard the operation with `if copies in 0..255`
   │ Note 2: counterexample: copies = -1

The counterexample, copies = -1, is an Int that no U8 can hold. A precondition that copies lies between 0 and 255 (chapter 5), or a value the verifier knows, as count in widths, makes the conversion safe.

2.3.6.4 More rules

2.3.7 When to use a fixed width

Which to use:

The number… Use
Is a count, a total or money in your own code Int
Is read or written by a device, a protocol or a file format with a set width the fixed-width type it names
Must wrap around on purpose, as in a checksum a fixed-width type and wrapping_add
Must stop at the end of the range, as a counter of labels left saturating_sub and its siblings
Crosses between the two to_int() one way, and a narrowing method, with its proof, the other

2.3.8 Check yourself: fixed-width integers

Change the first let of widths so that the U8 is computed:

src/widths.unadiff
--- a/src/widths.una
+++ b/src/widths.una
@@ -7 +7 @@
-  let copies: U8 = 200
+  let copies: U8 = 200 + 100

Does it still check? And in the original step, what does the last line print, with roll holding 500?

steps/17-widths/src/widths.unauna
  let roll: U16 = 500
  @console.print("{roll.saturating_sub(by: 600)} and {roll.wrapping_sub(by: 600)}")
Show the answer

It does not check:

Diagnostic
[U5001] Error: overflow obligation `200 + 100 in 0..255` is refuted

200 + 100 is 300, which a U8 cannot hold, and the verifier proves that the sum leaves the range. The last line of the original prints:

Output
0 and 65436

500 − 600 is −100. saturating_sub stops at 0. wrapping_sub wraps around the 65536 values of a U16: −100 + 65536 is 65436.

Next:2.4 Day-to-day: a packing slip