1666395480

# IntModN.jl: Ring(s) of Integers Modulo N; Polynomials; Factor Rings

## IntModN.jl

A pragmatic (meaning incomplete, and written by someone who needed this before he fully understood it) library for doing modular arithmetic.

The aim is not to encapsulate a large amount of theory, or to describe the relationships between different structures, but to enable arithmetic on various types, motivated largely by the practical needs of crypto code.

Incomplete; pull requests welcome.

## Examples

See the tests.

### Simultaneous Equations

``````julia> using IntModN

@zfield 2 begin
A = [1 1 1 0;
1 1 0 1;
1 0 1 1;
0 1 1 1]
b = [1, 1, 0, 1]
x = A\b
@assert x == [0, 1, 0, 0]
end
``````

### Polynomial Arithmetic

``````julia> x = X(GF2)
ZP(ZField{2,Int64},1,0)

julia> a = x^3 + x^2 + 1
ZP(ZField{2,Int64},1,1,0,1)

julia> b = x^2 + 1
ZP(ZField{2,Int64},1,0,1)

julia> p, q = divrem(a, b)
(ZP(ZField{2,Int64},1,1),ZP(ZField{2,Int64},1,0))

julia> println(p * b + q)
x^3 + x^2 + 1 mod 2
``````

### Fast Polynomials in GF(2)

The examples above could have used any modulus. I chose GF(2) only because it is common.

However, the following works only in GF(2) (the trade-off for the lack of flexibility is speed and compactness - these are encoded as bit patterns):

``````julia> x = GF2X(Uint8)
GF2Poly{Uint8}(2)

julia> a = x^3 + x^2 + 1
GF2Poly{Uint8}(13)

julia> b = x^2 + 1
GF2Poly{Uint8}(5)

julia> p, q = divrem(a, b)
(GF2Poly{Uint8}(3),GF2Poly{Uint8}(2))

julia> @assert a == p * b + q
``````

### Rijndael

The multiplication described here:

``````julia> x = GF2X(Uint)
GF2Poly{UInt64}(2)

julia> rijndael = x^8 + x^4 + x^3 + x + 1
GF2Poly{UInt64}(283)

julia> print(ZF(rijndael, x^7 + x^6 + x^3 + x) * ZF(rijndael, x^6 + x^4 + x +
1))
1 mod 2 mod x^8 + x^4 + x^3 + x + 1 mod 2
``````

Note that `rinjdael` here requires 9 bits of storage; there is no currently representation with an implicit msb.

## Types

`Residue <: Integer` - abstract superclass for (almost) everything below. Used to provide some common utilities (like automatic promotion from integers).

### Integers Modulo N

`ZModN{N,I<:Integer} <: Residue` - abstract superclass for integers modulo some value, where `N` is the modulus, and so typically an `Int` (yes, that's a integer as a type, not a value), and `I`

This has two concrete subclasses, because when `N` is a prime number we can define a multiplicative inverse.

`ZRing{N, I<:Integer} <: ZModN{N,I}` - the general case.

`ZField{N, I<:Integer} <: ZModN{N,I}` - assumes that `N` is prime, and so includes division.

These constructors can be used directly, but do not check that arguments are consistent with assumptions made in the code (values within range, etc).

The associated functions `ZR()` and `ZF()` are more suitable for "normal" use (but still do not check primality for fields), and include support for factory functions:

``````julia> ZF(3, 5, UInt8)
ZField{3,UInt8}(2)

julia> ZF(3, 5)
ZField{3,Int64}(2)

julia> GF3 = ZF(3)
(anonymous function)

julia> GF3(5)
ZField{3,Int64}(2)
``````

The macros `@zring` and `@zfield` can also be used to convert all integers with scope:

``````julia> @zring 4 begin
A = [1 2 3 4 5]
end
1x5 Array{IntModN.ZRing{4,Int64},2}:
1  2  3  0  1
``````

### Polynomials

`Poly <: Residue` - abstract superclass for polynomials. All share some basic conventions about accessing coefficients (with `[]`) and iterators.

The types below all form rings, not fields, because polynomials do not have inverses.

Note: Originally, the code used Polynomial.jl, but that had some weird design decisions so I wrote my own code. Since then, Polynomials.jl fixed some of the issues, so at some point it may make sense to revert to that package.

#### Polynomials With Integral Coefficients

`ZPoly{I<:Integer} <: Poly` - a simple wrapper around an array of integral coefficients (including `ZModN` subclasses). The coefficients are in the "usual" order, so `[i]` gives the ith coefficient, and the leading coefficient is always non-zero (or the array is empty).

As with integers mod N, the constructor can be used directly, but it is generally preferable to use `ZP()`, which has various forms.

In addition, there's support for the natural syntax `x^n...` via `X()`:

``````julia> x = X(ZF(2))
ZP(IntModN.ZField{2,Int64},1,0)

julia> x^3 + x
ZP(IntModN.ZField{2,Int64},1,0,1,0)
``````

#### Polynomials over GF(2)

`GF2Poly{U<:Unsigned} <: Poly` - specialized support for polynomials over GF(2). Coefficients can only be 0 or 1, so we can use bit fields (integers) for their values.

As always, you can use the constructor directly, or the utilities `GF2P()` and `GF2X()`.

The bit pattern can be displayed with `bits()` and addition is binary xor:

``````julia> x = GF2X(Uint8)
GF2Poly{UInt8}(2)

julia> a = x^7 + x^3
GF2Poly{UInt8}(136)

julia> b = x^3 + x^2 + 1
GF2Poly{UInt8}(13)

julia> a+b
GF2Poly{UInt8}(133)

julia> bits(a), bits(b), bits(a+b)
("10001000","00001101","10000101")
``````

### Quotient (Factor) Rings

These used to be a spearate type, but can now be handled as `ZRing()` and `ZField()` with polynomial arguments. The latter is appropriate when the ideal is irreducible (maximal) (I think).

See the Rijndael example.

WARNING the current tagged version gives warnings in the latest 0.4, while the tests on the github trunk fail. I do not have time right now to maintain this code, so caveat emptor. Sorry.

Author: Andrewcooke
Source Code: https://github.com/andrewcooke/IntModN.jl

1656151740

## Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

## How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

``````dev_dependencies:
test_cov_console: ^0.2.2
``````

## How to run

### run the following command to make sure all flutter library is up-to-date

``````flutter pub get
Running "flutter pub get" in coverage...                            0.5s
``````

### run the following command to generate lcov.info on coverage directory

``````flutter test --coverage
00:02 +1: All tests passed!
``````

### run the tool to generate report from lcov.info

``````flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

## Optional parameter

``````If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
If the value >= MINIMUM, it will print PASSED, otherwise FAILED
Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help
``````

### example run the tool with parameters

``````flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### report for multiple lcov.info files (-m, --multi)

``````It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
``````

### Output to CSV file (-c, --csv, -o, --output)

``````flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""``````

## Use this package as an executable

### Install it

You can install the package from the command line:

``dart pub global activate test_cov_console``

### Use it

The package has the following executables:

``````\$ test_cov_console
``````

## Use this package as a library

### Depend on it

Run this command:

With Dart:

`` \$ dart pub add test_cov_console``

With Flutter:

`` \$ flutter pub add test_cov_console``

This will add a line like this to your package's pubspec.yaml (and run an implicit `dart pub get`):

``````dependencies:
test_cov_console: ^0.2.2``````

Alternatively, your editor might support `dart pub get` or `flutter pub get`. Check the docs for your editor to learn more.

### Import it

Now in your Dart code, you can use:

``import 'package:test_cov_console/test_cov_console.dart';``

example/lib/main.dart

``````import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);

// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'\$_counter',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}``````

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console

1666395480

## IntModN.jl

A pragmatic (meaning incomplete, and written by someone who needed this before he fully understood it) library for doing modular arithmetic.

The aim is not to encapsulate a large amount of theory, or to describe the relationships between different structures, but to enable arithmetic on various types, motivated largely by the practical needs of crypto code.

Incomplete; pull requests welcome.

## Examples

See the tests.

### Simultaneous Equations

``````julia> using IntModN

@zfield 2 begin
A = [1 1 1 0;
1 1 0 1;
1 0 1 1;
0 1 1 1]
b = [1, 1, 0, 1]
x = A\b
@assert x == [0, 1, 0, 0]
end
``````

### Polynomial Arithmetic

``````julia> x = X(GF2)
ZP(ZField{2,Int64},1,0)

julia> a = x^3 + x^2 + 1
ZP(ZField{2,Int64},1,1,0,1)

julia> b = x^2 + 1
ZP(ZField{2,Int64},1,0,1)

julia> p, q = divrem(a, b)
(ZP(ZField{2,Int64},1,1),ZP(ZField{2,Int64},1,0))

julia> println(p * b + q)
x^3 + x^2 + 1 mod 2
``````

### Fast Polynomials in GF(2)

The examples above could have used any modulus. I chose GF(2) only because it is common.

However, the following works only in GF(2) (the trade-off for the lack of flexibility is speed and compactness - these are encoded as bit patterns):

``````julia> x = GF2X(Uint8)
GF2Poly{Uint8}(2)

julia> a = x^3 + x^2 + 1
GF2Poly{Uint8}(13)

julia> b = x^2 + 1
GF2Poly{Uint8}(5)

julia> p, q = divrem(a, b)
(GF2Poly{Uint8}(3),GF2Poly{Uint8}(2))

julia> @assert a == p * b + q
``````

### Rijndael

The multiplication described here:

``````julia> x = GF2X(Uint)
GF2Poly{UInt64}(2)

julia> rijndael = x^8 + x^4 + x^3 + x + 1
GF2Poly{UInt64}(283)

julia> print(ZF(rijndael, x^7 + x^6 + x^3 + x) * ZF(rijndael, x^6 + x^4 + x +
1))
1 mod 2 mod x^8 + x^4 + x^3 + x + 1 mod 2
``````

Note that `rinjdael` here requires 9 bits of storage; there is no currently representation with an implicit msb.

## Types

`Residue <: Integer` - abstract superclass for (almost) everything below. Used to provide some common utilities (like automatic promotion from integers).

### Integers Modulo N

`ZModN{N,I<:Integer} <: Residue` - abstract superclass for integers modulo some value, where `N` is the modulus, and so typically an `Int` (yes, that's a integer as a type, not a value), and `I`

This has two concrete subclasses, because when `N` is a prime number we can define a multiplicative inverse.

`ZRing{N, I<:Integer} <: ZModN{N,I}` - the general case.

`ZField{N, I<:Integer} <: ZModN{N,I}` - assumes that `N` is prime, and so includes division.

These constructors can be used directly, but do not check that arguments are consistent with assumptions made in the code (values within range, etc).

The associated functions `ZR()` and `ZF()` are more suitable for "normal" use (but still do not check primality for fields), and include support for factory functions:

``````julia> ZF(3, 5, UInt8)
ZField{3,UInt8}(2)

julia> ZF(3, 5)
ZField{3,Int64}(2)

julia> GF3 = ZF(3)
(anonymous function)

julia> GF3(5)
ZField{3,Int64}(2)
``````

The macros `@zring` and `@zfield` can also be used to convert all integers with scope:

``````julia> @zring 4 begin
A = [1 2 3 4 5]
end
1x5 Array{IntModN.ZRing{4,Int64},2}:
1  2  3  0  1
``````

### Polynomials

`Poly <: Residue` - abstract superclass for polynomials. All share some basic conventions about accessing coefficients (with `[]`) and iterators.

The types below all form rings, not fields, because polynomials do not have inverses.

Note: Originally, the code used Polynomial.jl, but that had some weird design decisions so I wrote my own code. Since then, Polynomials.jl fixed some of the issues, so at some point it may make sense to revert to that package.

#### Polynomials With Integral Coefficients

`ZPoly{I<:Integer} <: Poly` - a simple wrapper around an array of integral coefficients (including `ZModN` subclasses). The coefficients are in the "usual" order, so `[i]` gives the ith coefficient, and the leading coefficient is always non-zero (or the array is empty).

As with integers mod N, the constructor can be used directly, but it is generally preferable to use `ZP()`, which has various forms.

In addition, there's support for the natural syntax `x^n...` via `X()`:

``````julia> x = X(ZF(2))
ZP(IntModN.ZField{2,Int64},1,0)

julia> x^3 + x
ZP(IntModN.ZField{2,Int64},1,0,1,0)
``````

#### Polynomials over GF(2)

`GF2Poly{U<:Unsigned} <: Poly` - specialized support for polynomials over GF(2). Coefficients can only be 0 or 1, so we can use bit fields (integers) for their values.

As always, you can use the constructor directly, or the utilities `GF2P()` and `GF2X()`.

The bit pattern can be displayed with `bits()` and addition is binary xor:

``````julia> x = GF2X(Uint8)
GF2Poly{UInt8}(2)

julia> a = x^7 + x^3
GF2Poly{UInt8}(136)

julia> b = x^3 + x^2 + 1
GF2Poly{UInt8}(13)

julia> a+b
GF2Poly{UInt8}(133)

julia> bits(a), bits(b), bits(a+b)
("10001000","00001101","10000101")
``````

### Quotient (Factor) Rings

These used to be a spearate type, but can now be handled as `ZRing()` and `ZField()` with polynomial arguments. The latter is appropriate when the ideal is irreducible (maximal) (I think).

See the Rijndael example.

WARNING the current tagged version gives warnings in the latest 0.4, while the tests on the github trunk fail. I do not have time right now to maintain this code, so caveat emptor. Sorry.

Author: Andrewcooke
Source Code: https://github.com/andrewcooke/IntModN.jl

1640144506

## Rust For Beginners Tutorial - Strings

In this video we're taking a look at the String, &String and &str types in Rust!

Exercise solutions: https://github.com/PascalPrecht/rustlings/commits/solutions

---
0:00 Intro
0:09 Exercise 1
4:47 Exercise 2
10:38 Outro

## Strings

There are two types of strings in Rust: `String` and `&str`.

A `String` is stored as a vector of bytes (`Vec<u8>`), but guaranteed to always be a valid UTF-8 sequence. `String` is heap allocated, growable and not null terminated.

`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and can be used to view into a `String`, just like `&[T]` is a view into `Vec<T>`.

``````fn main() {
// (all the type annotations are superfluous)
// A reference to a string allocated in read only memory
let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
println!("Pangram: {}", pangram);

// Iterate over words in reverse, no new string is allocated
println!("Words in reverse");
for word in pangram.split_whitespace().rev() {
println!("> {}", word);
}

// Copy chars into a vector, sort and remove duplicates
let mut chars: Vec<char> = pangram.chars().collect();
chars.sort();
chars.dedup();

// Create an empty and growable `String`
let mut string = String::new();
for c in chars {
// Insert a char at the end of string
string.push(c);
// Insert a string at the end of string
string.push_str(", ");
}

// The trimmed string is a slice to the original string, hence no new
// allocation is performed
let chars_to_trim: &[char] = &[' ', ','];
let trimmed_str: &str = string.trim_matches(chars_to_trim);
println!("Used characters: {}", trimmed_str);

// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the modified string there
let bob: String = alice.replace("dog", "cat");

println!("Alice says: {}", alice);
println!("Bob says: {}", bob);
}
``````

More `str`/`String` methods can be found under the std::str and std::string modules

## Literals and escapes

There are multiple ways to write string literals with special characters in them. All result in a similar `&str` so it's best to use the form that is the most convenient to write. Similarly there are multiple ways to write byte string literals, which all result in `&[u8; N]`.

Generally special characters are escaped with a backslash character: `\`. This way you can add any character to your string, even unprintable ones and ones that you don't know how to type. If you want a literal backslash, escape it with another one: `\\`

String or character literal delimiters occuring within a literal must be escaped: `"\""`, `'\''`.

``````fn main() {
// You can use escapes to write bytes by their hexadecimal values...
let byte_escape = "I'm writing \x52\x75\x73\x74!";
println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);

// ...or Unicode code points.
let unicode_codepoint = "\u{211D}";
let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";

println!("Unicode character {} (U+211D) is called {}",
unicode_codepoint, character_name );

let long_string = "String literals
can span multiple lines.
The linebreak and indentation here ->\
<- can be escaped too!";
println!("{}", long_string);
}
``````

Sometimes there are just too many characters that need to be escaped or it's just much more convenient to write a string out as-is. This is where raw string literals come into play.

``````fn main() {
let raw_str = r"Escapes don't work here: \x3F \u{211D}";
println!("{}", raw_str);

// If you need quotes in a raw string, add a pair of #s
let quotes = r#"And then I said: "There is no escape!""#;
println!("{}", quotes);

// If you need "# in your string, just use more #s in the delimiter.
// There is no limit for the number of #s you can use.
let longer_delimiter = r###"A string with "# in it. And even "##!"###;
println!("{}", longer_delimiter);
}
``````

Want a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8). Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!

``````use std::str;

fn main() {
// Note that this is not actually a `&str`
let bytestring: &[u8; 21] = b"this is a byte string";

// Byte arrays don't have the `Display` trait, so printing them is a bit limited
println!("A byte string: {:?}", bytestring);

// Byte strings can have byte escapes...
let escaped = b"\x52\x75\x73\x74 as bytes";
// ...but no unicode escapes
// let escaped = b"\u{211D} is not allowed";
println!("Some escaped bytes: {:?}", escaped);

// Raw byte strings work just like raw strings
let raw_bytestring = br"\u{211D} is not escaped here";
println!("{:?}", raw_bytestring);

// Converting a byte array to `str` can fail
if let Ok(my_str) = str::from_utf8(raw_bytestring) {
println!("And the same as text: '{}'", my_str);
}

let _quotes = br#"You can also use "fancier" formatting, \
like with normal raw strings"#;

// Byte strings don't have to be UTF-8
let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS

// But then they can't always be converted to `str`
match str::from_utf8(shift_jis) {
Ok(my_str) => println!("Conversion successful: '{}'", my_str),
Err(e) => println!("Conversion failed: {:?}", e),
};
}
``````

For conversions between character encodings check out the encoding crate.

A more detailed listing of the ways to write string literals and escape characters is given in the 'Tokens' chapter of the Rust Reference.

#rust #programming #developer

1636360749

## Std Library Types - Rust By Example

The `std` library provides many custom types which expands drastically on the `primitives`. Some of these include:

• growable `String`s like: `"hello world"`
• growable vectors: `[1, 2, 3]`
• optional types: `Option<i32>`
• error handling types: `Result<i32, i32>`
• heap allocated pointers: `Box<i32>`

## Box, stack and heap

All values in Rust are stack allocated by default. Values can be boxed (allocated on the heap) by creating a `Box<T>`. A box is a smart pointer to a heap allocated value of type `T`. When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed.

Boxed values can be dereferenced using the `*` operator; this removes one layer of indirection.

``````use std::mem;

#[derive(Debug, Clone, Copy)]
struct Point {
x: f64,
y: f64,
}

// A Rectangle can be specified by where its top left and bottom right
// corners are in space
struct Rectangle {
top_left: Point,
bottom_right: Point,
}

fn origin() -> Point {
Point { x: 0.0, y: 0.0 }
}

fn boxed_origin() -> Box<Point> {
// Allocate this point on the heap, and return a pointer to it
Box::new(Point { x: 0.0, y: 0.0 })
}

fn main() {
// (all the type annotations are superfluous)
// Stack allocated variables
let point: Point = origin();
let rectangle: Rectangle = Rectangle {
top_left: origin(),
bottom_right: Point { x: 3.0, y: -4.0 }
};

// Heap allocated rectangle
let boxed_rectangle: Box<Rectangle> = Box::new(Rectangle {
top_left: origin(),
bottom_right: Point { x: 3.0, y: -4.0 },
});

// The output of functions can be boxed
let boxed_point: Box<Point> = Box::new(origin());

// Double indirection
let box_in_a_box: Box<Box<Point>> = Box::new(boxed_origin());

println!("Point occupies {} bytes on the stack",
mem::size_of_val(&point));
println!("Rectangle occupies {} bytes on the stack",
mem::size_of_val(&rectangle));

// box size == pointer size
println!("Boxed point occupies {} bytes on the stack",
mem::size_of_val(&boxed_point));
println!("Boxed rectangle occupies {} bytes on the stack",
mem::size_of_val(&boxed_rectangle));
println!("Boxed box occupies {} bytes on the stack",
mem::size_of_val(&box_in_a_box));

// Copy the data contained in `boxed_point` into `unboxed_point`
let unboxed_point: Point = *boxed_point;
println!("Unboxed point occupies {} bytes on the stack",
mem::size_of_val(&unboxed_point));
}
``````

## Vectors

Vectors are re-sizable arrays. Like slices, their size is not known at compile time, but they can grow or shrink at any time. A vector is represented using 3 parameters:

• pointer to the data
• length
• capacity

The capacity indicates how much memory is reserved for the vector. The vector can grow as long as the length is smaller than the capacity. When this threshold needs to be surpassed, the vector is reallocated with a larger capacity.

``````fn main() {
// Iterators can be collected into vectors
let collected_iterator: Vec<i32> = (0..10).collect();
println!("Collected (0..10) into: {:?}", collected_iterator);

// The `vec!` macro can be used to initialize a vector
let mut xs = vec![1i32, 2, 3];
println!("Initial vector: {:?}", xs);

// Insert new element at the end of the vector
println!("Push 4 into the vector");
xs.push(4);
println!("Vector: {:?}", xs);

// Error! Immutable vectors can't grow
collected_iterator.push(0);
// FIXME ^ Comment out this line

// The `len` method yields the number of elements currently stored in a vector
println!("Vector length: {}", xs.len());

// Indexing is done using the square brackets (indexing starts at 0)
println!("Second element: {}", xs[1]);

// `pop` removes the last element from the vector and returns it
println!("Pop last element: {:?}", xs.pop());

// Out of bounds indexing yields a panic
println!("Fourth element: {}", xs[3]);
// FIXME ^ Comment out this line

// `Vector`s can be easily iterated over
println!("Contents of xs:");
for x in xs.iter() {
println!("> {}", x);
}

// A `Vector` can also be iterated over while the iteration
// count is enumerated in a separate variable (`i`)
for (i, x) in xs.iter().enumerate() {
println!("In position {} we have value {}", i, x);
}

// Thanks to `iter_mut`, mutable `Vector`s can also be iterated
// over in a way that allows modifying each value
for x in xs.iter_mut() {
*x *= 3;
}
println!("Updated vector: {:?}", xs);
}
``````

More `Vec` methods can be found under the std::vec module

## Strings

There are two types of strings in Rust: `String` and `&str`.

A `String` is stored as a vector of bytes (`Vec<u8>`), but guaranteed to always be a valid UTF-8 sequence. `String` is heap allocated, growable and not null terminated.

`&str` is a slice (`&[u8]`) that always points to a valid UTF-8 sequence, and can be used to view into a `String`, just like `&[T]` is a view into `Vec<T>`.

``````fn main() {
// (all the type annotations are superfluous)
// A reference to a string allocated in read only memory
let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
println!("Pangram: {}", pangram);

// Iterate over words in reverse, no new string is allocated
println!("Words in reverse");
for word in pangram.split_whitespace().rev() {
println!("> {}", word);
}

// Copy chars into a vector, sort and remove duplicates
let mut chars: Vec<char> = pangram.chars().collect();
chars.sort();
chars.dedup();

// Create an empty and growable `String`
let mut string = String::new();
for c in chars {
// Insert a char at the end of string
string.push(c);
// Insert a string at the end of string
string.push_str(", ");
}

// The trimmed string is a slice to the original string, hence no new
// allocation is performed
let chars_to_trim: &[char] = &[' ', ','];
let trimmed_str: &str = string.trim_matches(chars_to_trim);
println!("Used characters: {}", trimmed_str);

// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the modified string there
let bob: String = alice.replace("dog", "cat");

println!("Alice says: {}", alice);
println!("Bob says: {}", bob);
}
``````

More `str`/`String` methods can be found under the std::str and std::string modules

### Literals and escapes

There are multiple ways to write string literals with special characters in them. All result in a similar `&str` so it's best to use the form that is the most convenient to write. Similarly there are multiple ways to write byte string literals, which all result in `&[u8; N]`.

Generally special characters are escaped with a backslash character: `\`. This way you can add any character to your string, even unprintable ones and ones that you don't know how to type. If you want a literal backslash, escape it with another one: `\\`

String or character literal delimiters occuring within a literal must be escaped: `"\""`, `'\''`.

``````fn main() {
// You can use escapes to write bytes by their hexadecimal values...
let byte_escape = "I'm writing \x52\x75\x73\x74!";
println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);

// ...or Unicode code points.
let unicode_codepoint = "\u{211D}";
let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";

println!("Unicode character {} (U+211D) is called {}",
unicode_codepoint, character_name );

let long_string = "String literals
can span multiple lines.
The linebreak and indentation here ->\
<- can be escaped too!";
println!("{}", long_string);
}
``````

Sometimes there are just too many characters that need to be escaped or it's just much more convenient to write a string out as-is. This is where raw string literals come into play.

``````fn main() {
let raw_str = r"Escapes don't work here: \x3F \u{211D}";
println!("{}", raw_str);

// If you need quotes in a raw string, add a pair of #s
let quotes = r#"And then I said: "There is no escape!""#;
println!("{}", quotes);

// If you need "# in your string, just use more #s in the delimiter.
// There is no limit for the number of #s you can use.
let longer_delimiter = r###"A string with "# in it. And even "##!"###;
println!("{}", longer_delimiter);
}
``````

Want a string that's not UTF-8? (Remember, `str` and `String` must be valid UTF-8). Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!

``````use std::str;

fn main() {
// Note that this is not actually a `&str`
let bytestring: &[u8; 21] = b"this is a byte string";

// Byte arrays don't have the `Display` trait, so printing them is a bit limited
println!("A byte string: {:?}", bytestring);

// Byte strings can have byte escapes...
let escaped = b"\x52\x75\x73\x74 as bytes";
// ...but no unicode escapes
// let escaped = b"\u{211D} is not allowed";
println!("Some escaped bytes: {:?}", escaped);

// Raw byte strings work just like raw strings
let raw_bytestring = br"\u{211D} is not escaped here";
println!("{:?}", raw_bytestring);

// Converting a byte array to `str` can fail
if let Ok(my_str) = str::from_utf8(raw_bytestring) {
println!("And the same as text: '{}'", my_str);
}

let _quotes = br#"You can also use "fancier" formatting, \
like with normal raw strings"#;

// Byte strings don't have to be UTF-8
let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS

// But then they can't always be converted to `str`
match str::from_utf8(shift_jis) {
Ok(my_str) => println!("Conversion successful: '{}'", my_str),
Err(e) => println!("Conversion failed: {:?}", e),
};
}
``````

For conversions between character encodings check out the encoding crate.

A more detailed listing of the ways to write string literals and escape characters is given in the 'Tokens' chapter of the Rust Reference.

## `Option`

Sometimes it's desirable to catch the failure of some parts of a program instead of calling `panic!`; this can be accomplished using the `Option` enum.

The `Option<T>` enum has two variants:

• `None`, to indicate failure or lack of value, and
• `Some(value)`, a tuple struct that wraps a `value` with type `T`.
``````// An integer division that doesn't `panic!`
fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
if divisor == 0 {
// Failure is represented as the `None` variant
None
} else {
// Result is wrapped in a `Some` variant
Some(dividend / divisor)
}
}

// This function handles a division that may not succeed
fn try_division(dividend: i32, divisor: i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}

fn main() {
try_division(4, 2);
try_division(1, 0);

// Binding `None` to a variable needs to be type annotated
let none: Option<i32> = None;
let _equivalent_none = None::<i32>;

let optional_float = Some(0f32);

// Unwrapping a `Some` variant will extract the value wrapped.
println!("{:?} unwraps to {:?}", optional_float, optional_float.unwrap());

// Unwrapping a `None` variant will `panic!`
println!("{:?} unwraps to {:?}", none, none.unwrap());
}
``````

## `Result`

We've seen that the `Option` enum can be used as a return value from functions that may fail, where `None` can be returned to indicate failure. However, sometimes it is important to express why an operation failed. To do this we have the `Result` enum.

The `Result<T, E>` enum has two variants:

• `Ok(value)` which indicates that the operation succeeded, and wraps the `value` returned by the operation. (`value` has type `T`)
• `Err(why)`, which indicates that the operation failed, and wraps `why`, which (hopefully) explains the cause of the failure. (`why` has type `E`)
``````mod checked {
// Mathematical "errors" we want to catch
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}

pub type MathResult = Result<f64, MathError>;

pub fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
// This operation would `fail`, instead let's return the reason of
// the failure wrapped in `Err`
Err(MathError::DivisionByZero)
} else {
// This operation is valid, return the result wrapped in `Ok`
Ok(x / y)
}
}

pub fn sqrt(x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeSquareRoot)
} else {
Ok(x.sqrt())
}
}

pub fn ln(x: f64) -> MathResult {
if x <= 0.0 {
Err(MathError::NonPositiveLogarithm)
} else {
Ok(x.ln())
}
}
}

// `op(x, y)` === `sqrt(ln(x / y))`
fn op(x: f64, y: f64) -> f64 {
// This is a three level match pyramid!
match checked::div(x, y) {
Err(why) => panic!("{:?}", why),
Ok(ratio) => match checked::ln(ratio) {
Err(why) => panic!("{:?}", why),
Ok(ln) => match checked::sqrt(ln) {
Err(why) => panic!("{:?}", why),
Ok(sqrt) => sqrt,
},
},
}
}

fn main() {
// Will this fail?
println!("{}", op(1.0, 10.0));
}
``````

### `?`

Chaining results using match can get pretty untidy; luckily, the `?` operator can be used to make things pretty again. `?` is used at the end of an expression returning a `Result`, and is equivalent to a match expression, where the `Err(err)` branch expands to an early `Err(From::from(err))`, and the `Ok(ok)` branch expands to an `ok` expression.

``````mod checked {
#[derive(Debug)]
enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}

type MathResult = Result<f64, MathError>;

fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} else {
Ok(x / y)
}
}

fn sqrt(x: f64) -> MathResult {
if x < 0.0 {
Err(MathError::NegativeSquareRoot)
} else {
Ok(x.sqrt())
}
}

fn ln(x: f64) -> MathResult {
if x <= 0.0 {
Err(MathError::NonPositiveLogarithm)
} else {
Ok(x.ln())
}
}

// Intermediate function
fn op_(x: f64, y: f64) -> MathResult {
// if `div` "fails", then `DivisionByZero` will be `return`ed
let ratio = div(x, y)?;

// if `ln` "fails", then `NonPositiveLogarithm` will be `return`ed
let ln = ln(ratio)?;

sqrt(ln)
}

pub fn op(x: f64, y: f64) {
match op_(x, y) {
Err(why) => panic!("{}", match why {
MathError::NonPositiveLogarithm
=> "logarithm of non-positive number",
MathError::DivisionByZero
=> "division by zero",
MathError::NegativeSquareRoot
=> "square root of negative number",
}),
Ok(value) => println!("{}", value),
}
}
}

fn main() {
checked::op(1.0, 10.0);
}
``````

Be sure to check the documentation, as there are many methods to map/compose `Result`.

## `panic!`

The `panic!` macro can be used to generate a panic and start unwinding its stack. While unwinding, the runtime will take care of freeing all the resources owned by the thread by calling the destructor of all its objects.

Since we are dealing with programs with only one thread, `panic!` will cause the program to report the panic message and exit.

``````// Re-implementation of integer division (/)
fn division(dividend: i32, divisor: i32) -> i32 {
if divisor == 0 {
// Division by zero triggers a panic
panic!("division by zero");
} else {
dividend / divisor
}
}

fn main() {
// Heap allocated integer
let _x = Box::new(0i32);

// This operation will trigger a task failure
division(3, 0);

println!("This point won't be reached!");

// `_x` should get destroyed at this point
}
``````

Let's check that `panic!` doesn't leak memory.

``````\$ rustc panic.rs && valgrind ./panic
==4401== Memcheck, a memory error detector
==4401== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4401== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==4401== Command: ./panic
==4401==
thread '<main>' panicked at 'division by zero', panic.rs:5
==4401==
==4401== HEAP SUMMARY:
==4401==     in use at exit: 0 bytes in 0 blocks
==4401==   total heap usage: 18 allocs, 18 frees, 1,648 bytes allocated
==4401==
==4401== All heap blocks were freed -- no leaks are possible
==4401==
==4401== For counts of detected and suppressed errors, rerun with: -v
==4401== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
``````

## HashMap

Where vectors store values by an integer index, `HashMap`s store values by key. `HashMap` keys can be booleans, integers, strings, or any other type that implements the `Eq` and `Hash` traits. More on this in the next section.

Like vectors, `HashMap`s are growable, but HashMaps can also shrink themselves when they have excess space. You can create a HashMap with a certain starting capacity using `HashMap::with_capacity(uint)`, or use `HashMap::new()` to get a HashMap with a default initial capacity (recommended).

``````use std::collections::HashMap;

fn call(number: &str) -> &str {
match number {
"798-1364" => "We're sorry, the call cannot be completed as dialed.
Please hang up and try again.",
"645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
What can I get for you today?",
_ => "Hi! Who is this again?"
}
}

fn main() {
let mut contacts = HashMap::new();

contacts.insert("Daniel", "798-1364");
contacts.insert("Ashley", "645-7689");
contacts.insert("Katie", "435-8291");
contacts.insert("Robert", "956-1745");

// Takes a reference and returns Option<&V>
match contacts.get(&"Daniel") {
Some(&number) => println!("Calling Daniel: {}", call(number)),
_ => println!("Don't have Daniel's number."),
}

// `HashMap::insert()` returns `None`
// if the inserted value is new, `Some(value)` otherwise
contacts.insert("Daniel", "164-6743");

match contacts.get(&"Ashley") {
Some(&number) => println!("Calling Ashley: {}", call(number)),
_ => println!("Don't have Ashley's number."),
}

contacts.remove(&"Ashley");

// `HashMap::iter()` returns an iterator that yields
// (&'a key, &'a value) pairs in arbitrary order.
for (contact, &number) in contacts.iter() {
println!("Calling {}: {}", contact, call(number));
}
}
``````

For more information on how hashing and hash maps (sometimes called hash tables) work, have a look at Hash Table Wikipedia

### Alternate/custom key types

Any type that implements the `Eq` and `Hash` traits can be a key in `HashMap`. This includes:

• `bool` (though not very useful since there is only two possible keys)
• `int`, `uint`, and all variations thereof
• `String` and `&str` (protip: you can have a `HashMap` keyed by `String` and call `.get()` with an `&str`)

Note that `f32` and `f64` do not implement `Hash`, likely because floating-point precision errors would make using them as hashmap keys horribly error-prone.

All collection classes implement `Eq` and `Hash` if their contained type also respectively implements `Eq` and `Hash`. For example, `Vec<T>` will implement `Hash` if `T` implements `Hash`.

You can easily implement `Eq` and `Hash` for a custom type with just one line: `#[derive(PartialEq, Eq, Hash)]`

The compiler will do the rest. If you want more control over the details, you can implement `Eq` and/or `Hash` yourself. This guide will not cover the specifics of implementing `Hash`.

To play around with using a `struct` in `HashMap`, let's try making a very simple user logon system:

``````use std::collections::HashMap;

// Eq requires that you derive PartialEq on the type.
#[derive(PartialEq, Eq, Hash)]
struct Account<'a>{
}

struct AccountInfo<'a>{
name: &'a str,
email: &'a str,
}

type Accounts<'a> = HashMap<Account<'a>, AccountInfo<'a>>;

fn try_logon<'a>(accounts: &Accounts<'a>,
println!("Attempting logon...");

let logon = Account {
};

match accounts.get(&logon) {
Some(account_info) => {
println!("Successful logon!");
println!("Name: {}", account_info.name);
println!("Email: {}", account_info.email);
},
}
}

fn main(){
let mut accounts: Accounts = HashMap::new();

let account = Account {
};

let account_info = AccountInfo {
name: "John Everyman",
email: "j.everyman@email.com",
};

accounts.insert(account, account_info);

try_logon(&accounts, "j.everyman", "psasword123");

}
``````

### HashSet

Consider a `HashSet` as a `HashMap` where we just care about the keys ( `HashSet<T>` is, in actuality, just a wrapper around `HashMap<T, ()>`).

"What's the point of that?" you ask. "I could just store the keys in a `Vec`."

A `HashSet`'s unique feature is that it is guaranteed to not have duplicate elements. That's the contract that any set collection fulfills. `HashSet` is just one implementation. (see also: `BTreeSet`)

If you insert a value that is already present in the `HashSet`, (i.e. the new value is equal to the existing and they both have the same hash), then the new value will replace the old.

This is great for when you never want more than one of something, or when you want to know if you've already got something.

But sets can do more than that.

Sets have 4 primary operations (all of the following calls return an iterator):

`union`: get all the unique elements in both sets.

`difference`: get all the elements that are in the first set but not the second.

`intersection`: get all the elements that are only in both sets.

`symmetric_difference`: get all the elements that are in one set or the other, but not both.

Try all of these in the following example:

``````use std::collections::HashSet;

fn main() {
let mut a: HashSet<i32> = vec![1i32, 2, 3].into_iter().collect();
let mut b: HashSet<i32> = vec![2i32, 3, 4].into_iter().collect();

assert!(a.insert(4));
assert!(a.contains(&4));

// `HashSet::insert()` returns false if
// there was a value already present.
assert!(b.insert(4), "Value 4 is already in set B!");
// FIXME ^ Comment out this line

b.insert(5);

// If a collection's element type implements `Debug`,
// then the collection implements `Debug`.
// It usually prints its elements in the format `[elem1, elem2, ...]`
println!("A: {:?}", a);
println!("B: {:?}", b);

// Print [1, 2, 3, 4, 5] in arbitrary order
println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>());

// This should print [1]
println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>());

// Print [2, 3, 4] in arbitrary order.
println!("Intersection: {:?}", a.intersection(&b).collect::<Vec<&i32>>());

// Print [1, 5]
println!("Symmetric Difference: {:?}",
a.symmetric_difference(&b).collect::<Vec<&i32>>());
}
``````

(Examples are adapted from the documentation.)

## `Rc`

When multiple ownership is needed, `Rc`(Reference Counting) can be used. `Rc` keeps track of the number of the references which means the number of owners of the value wrapped inside an `Rc`.

Reference count of an `Rc` increases by 1 whenever an `Rc` is cloned, and decreases by 1 whenever one cloned `Rc` is dropped out of the scope. When an `Rc`'s reference count becomes zero, which means there are no owners remained, both the `Rc` and the value are all dropped.

Cloning an `Rc` never performs a deep copy. Cloning creates just another pointer to the wrapped value, and increments the count.

``````use std::rc::Rc;

fn main() {
let rc_examples = "Rc examples".to_string();
{
println!("--- rc_a is created ---");

let rc_a: Rc<String> = Rc::new(rc_examples);
println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));

{
println!("--- rc_a is cloned to rc_b ---");

let rc_b: Rc<String> = Rc::clone(&rc_a);
println!("Reference Count of rc_b: {}", Rc::strong_count(&rc_b));
println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));

// Two `Rc`s are equal if their inner values are equal
println!("rc_a and rc_b are equal: {}", rc_a.eq(&rc_b));

// We can use methods of a value directly
println!("Length of the value inside rc_a: {}", rc_a.len());
println!("Value of rc_b: {}", rc_b);

println!("--- rc_b is dropped out of scope ---");
}

println!("Reference Count of rc_a: {}", Rc::strong_count(&rc_a));

println!("--- rc_a is dropped out of scope ---");
}

// Error! `rc_examples` already moved into `rc_a`
// And when `rc_a` is dropped, `rc_examples` is dropped together
// println!("rc_examples: {}", rc_examples);
// TODO ^ Try uncommenting this line
}
``````

## Arc

When shared ownership between threads is needed, `Arc`(Atomic Reference Counted) can be used. This struct, via the `Clone` implementation can create a reference pointer for the location of a value in the memory heap while increasing the reference counter. As it shares ownership between threads, when the last reference pointer to a value is out of scope, the variable is dropped.

``````
fn main() {
use std::sync::Arc;

// This variable declaration is where its value is specified.
let apple = Arc::new("the same apple");

for _ in 0..10 {
// Here there is no value specification as it is a pointer to a reference
// in the memory heap.
let apple = Arc::clone(&apple);

// As Arc was used, threads can be spawned using the value allocated
// in the Arc variable pointer's location.
println!("{:?}", apple);
});
}
}

``````

Original article source at https://doc.rust-lang.org

#rust #programming #developer

1599278213

## Java Integer Cache: Why Integer.valueOf(127) == Integer.valueOf(127) Is True

The short answer to this question is, direct assignment of an `int` literal to an `Integer` reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts `Integer a = 127;` to `Integer a = Integer.valueOf(127);`.

The `Integer` class maintains an internal `IntegerCache` for integers which, by default, ranges from `-128 to 127` and `Integer.valueOf()` method returns objects of mentioned range from that cache. So `a == b` returns true because `a` and `b` both are pointing to the same object.

In order to understand the short answer, let’s first understand the Java types, all types in Java lies under two categories

1. Primitive Types: There are 8 primitive types (`byte``short``int``long``float``double``char`, and `boolean`) in Java, which holds their values directly in the form of binary bits.
2. For example, `int a = 5; int b = 5;` here `a` and `b` directly holds the binary value of 5, and if we try to compare `a` and `b` using `a == b`, we are actually comparing `5 == 5`, which returns true.
3. Reference Types: All types other than primitive types lies under the category of reference types, e.g. Classes, Interfaces, Enums, Arrays, etc. and reference types holds the address of the object instead of the object itself.
4. For example, `Integer a = new Integer(5); Integer b = new Integer(5)`, here, a and b do not hold the binary value of `5` instead `a` and `b` holds memory addresses of two separate objects where both objects contain a value `5`. So if we try to compare `a` and `b` using `a == b, ,`we are actually comparing those two separate memory addresses. Hence, we get `false`, to perform actual equality on `a` and `b` we need to perform `a.euqals(b)`.

Reference types are further divided into 4 categories:  Strong, Soft, Weak and Phantom References.

And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.

``````// Example of auto-boxing, here c is a reference type
``````

Integer c = 128; // Compiler converts this line to Integer c = Integer.valueOf(128);

``````// Example of auto-unboxing, here e is a primitive type
``````

int e = c; // Compiler converts this line to int e = c.intValue();

``````
Now, if we create two integer objects `a` and `b,` and try to compare them using the equality operator `==`, we will get `false` because both references are holding different-different objects

``````

Integer a = 128; // Compiler converts this line to Integer a = Integer.valueOf(128);

``````Integer b = 128; // Compiler converts this line to Integer b = Integer.valueOf(128);
``````

System.out.println(a == b); // Output – false

``````
But if we assign the value `127` to both `a` and `b` and try to compare them using the equality operator `==`, we will get `true` why?

``````

Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);

``````Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
``````

System.out.println(a == b); // Output – true

``````
As we can see in the code, we are assigning different objects to `a` and `b` but `a == b` can return true only if both `a` and `b` are pointing to the same object.

So, how does the comparison return true? what's actually happening here? are `a` and `b` pointing to the same object?

Well, until now, we know that the code `Integer a = 127;` is an example of auto-boxing and compiler automatically converts this line to `Integer a = Integer.valueOf(127);`.

So, it is the `Integer.valueOf()` method that is returning these integer objects, which means this method must be doing something under the hood.

And if we take a look at the source code of `Integer.valueOf()` method, we can clearly see that if the passed int literal `i` is greater than `IntegerCache.low` and less than `IntegerCache.high ,`then the method returns Integer objects from `IntegerCache`. Default values for `IntegerCache.low` and `IntegerCache.high` are `-128` and `127` respectively.

In other words, instead of creating and returning new integer objects, `Integer.valueOf()` method returns Integer objects from an internal `IntegerCache` if the passed `int` literal is greater than `-128` and less than `127`.``````

#java #cache #short #long #btye #integer cache #java integer