rust brain teasers

8
Extracted from: Rust Brain Teasers Exercise Your Mind This PDF file contains pages extracted from Rust Brain Teasers, published by the Pragmatic Bookshelf. For more information or to purchase a paperback or PDF copy, please visit http://www.pragprog.com. Note: This extract contains some colored text (particularly in code listing). This is available only in online versions of the books. The printed versions are black and white. Pagination might vary between the online and printed versions; the content is otherwise identical. Copyright © 2021 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. The Pragmatic Bookshelf Raleigh, North Carolina

Upload: others

Post on 26-Nov-2021

138 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Rust Brain Teasers

Extracted from:

Rust Brain TeasersExercise Your Mind

This PDF file contains pages extracted from Rust Brain Teasers, published by thePragmatic Bookshelf. For more information or to purchase a paperback or PDF

copy, please visit http://www.pragprog.com.

Note: This extract contains some colored text (particularly in code listing). Thisis available only in online versions of the books. The printed versions are blackand white. Pagination might vary between the online and printed versions; the

content is otherwise identical.

Copyright © 2021 The Pragmatic Programmers, LLC.

All rights reserved.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise,

without the prior consent of the publisher.

The Pragmatic BookshelfRaleigh, North Carolina

Page 2: Rust Brain Teasers
Page 3: Rust Brain Teasers
Page 4: Rust Brain Teasers

Rust Brain TeasersExercise Your Mind

Herbert Wolverson

The Pragmatic BookshelfRaleigh, North Carolina

Page 5: Rust Brain Teasers

Many of the designations used by manufacturers and sellers to distinguish their productsare claimed as trademarks. Where those designations appear in this book, and The PragmaticProgrammers, LLC was aware of a trademark claim, the designations have been printed ininitial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer,Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade-marks of The Pragmatic Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher assumesno responsibility for errors or omissions, or for damages that may result from the use ofinformation (including program listings) contained herein.

For our complete catalog of hands-on, practical, and Pragmatic content for software devel-opers, please visit https://pragprog.com.

For sales, volume licensing, and support, please contact [email protected].

For international rights, please contact [email protected].

Copyright © 2021 The Pragmatic Programmers, LLC.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording,or otherwise, without the prior consent of the publisher.

ISBN-13: 978-1-680509-17-5Encoded using the finest acid-free high-entropy binary digits.Book version: B1.0—September 29, 2021

Page 6: Rust Brain Teasers

Puzzle 14

Structure Sizing

structure_sizing/src/main.rsuse std::mem::size_of;

struct VeryImportantMessage {_message_type : u8,_destination : u16

}

fn main() {println!(

"VeryImportantMessage occupies {} bytes.",size_of::<VeryImportantMessage>()

);}

Guess The Output

Try to guess what the output is before moving to the next page.

• Click HERE to purchase this book now. discuss

Page 7: Rust Brain Teasers

The program will display the following output:

VeryImportantMessage occupies 4 bytes.

DiscussionOneByte and TwoBytes are sized as you would expect, occupying 1 and 2 bytesof memory, respectively. So, why does ThreeBytes occupy 4 bytes of memory?

By default, Rust makes two promises about the in-memory representation ofyour structures:

• Structures may be sized differently than their contents for performancereasons.

• Structures may store data in a different order internally than you specifiedif the optimizer believes it will aid performance.

Most modern CPUs align data on 32-bit boundaries in memory and cache.Accessing 8-bits (one byte) or 16-bits (two bytes) is fast because the CPUprovides primitives to do so, and the structures can be packed along 32-bitboundaries.

A 24-bit (3 byte) structure does not naturally align to a 32-bit memory map,so by default, Rust wastes 8-bits of memory per struct to ensure fast accessto the structure in your computer’s memory. This behavior is especiallyhelpful when you’re dealing with arrays or other contiguous blocks of 3-bytestructures because every other structure would start at the 24th bit of a 32-bit block, reducing cache and read efficiency.

Sometimes, this behavior can cause problems, though. For example:

• If you’re storing a very large number of 24-bit structures, wasting a byteper structure might exceed your memory allocation—especially onembedded systems.

• If you’re interoperating with another language, that language may expectyour structures to be exactly 24-bits in size. Conversely, a server writtenin Rust may add padding to structures—surprising the client with paddingbytes.

• Likewise, if you’re interoperating with other languages, letting Rust rear-range your data in memory can cause bizarre problems when passingdata to-and-from the other language.

Rust Brain Teasers • 4

• Click HERE to purchase this book now. discuss

Page 8: Rust Brain Teasers

Constraining Rust’s Optimizer

You can turn off both of Rust’s structure optimizations using a decorationnamed #[repr()], which gives you control over how a struct is represented inmemory:

• #[repr(C)] declares that you require interoperability with the C language.Rust won’t rearrange the content of your structure.

• #[repr(packed)] tells Rust not to waste space on your structure. This cancarry a small performance penalty but guarantees that structures areexactly the right size.

You can combine these decorations. For example, a structure decorated with#[repr(C, packed)] won’t rearrange or pad your structure:

#[repr(C, packed)]struct ReallyThreeBytes {

a : u8,b : u16

}

fn main() {println!("ReallyThreeBytes occupies {} bytes.", size_of::<ReallyThreeBytes>());

}

This code prints:

ReallyThreeBytes occupies 3 bytes.

Further Readingrepr(Rust)

https://doc.rust-lang.org/nomicon/repr-rust.html

Type Layouthttps://doc.rust-lang.org/reference/type-layout.html

Layout of structs and tupleshttps://rust-lang.github.io/unsafe-code-guidelines/layout/structs-and-tuples.html

• Click HERE to purchase this book now. discuss

Structure Sizing • 5