diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/404/index.html b/404/index.html index 2e03a23..510ca89 100644 --- a/404/index.html +++ b/404/index.html @@ -9,10 +9,8 @@ - - + + diff --git a/Constructors-and-Destructors-in-C/index.html b/Constructors-and-Destructors-in-C/index.html index 1bf6ed5..0b14af1 100644 --- a/Constructors-and-Destructors-in-C/index.html +++ b/Constructors-and-Destructors-in-C/index.html @@ -73,9 +73,9 @@

Constructors

#ifndef STACK_H
 #define STACK_H
 
-#include <stdio.h>   // printf
-#include <stdlib.h>  // calloc & free
-#include <stdbool.h> // true & false
+#include <stdio.h>   // printf
+#include <stdlib.h>  // calloc & free
+#include <stdbool.h> // true & false
 
 #define STACK_CAP 12
 
@@ -138,8 +138,8 @@ 

Constructors

Now the following program:

-
#include <stdio.h>
-#include "header.h"
+
#include <stdio.h>
+#include "header.h"
 
 int main() {
     printf("Inside main\n");
diff --git a/Crafting-Code-1/index.html b/Crafting-Code-1/index.html
index 9ccc034..676e04d 100644
--- a/Crafting-Code-1/index.html
+++ b/Crafting-Code-1/index.html
@@ -75,13 +75,13 @@ 

Crafting Code - Building Common Interfaces

And that’ll require the user to import his/her desired function or set of functions as needed. This is fine, but wouldn’t it be better if you could provide only one function that does all these operations? We’re going to call this function a common interface, but this procedure is called a passthrough in the professional field. A passthrough function is a multi-purpose entry point to a set of different classes or functions. In the case of our Math library, we could have our passthrough function written as follows:

-
fn passthrough(operation: &'static str, op1: f32, op2: f32) -> f32 {
+
fn passthrough(operation: &'static str, op1: f32, op2: f32) -> f32 {
   return match operation {
     "+" => add(op1, op2),
     "-" => sub(op1, op2),
     "*" => mul(op1, op2),
     "/" => div(op1, op2),
-    _ => 0 as f32, //Return 0 if unknown operation. Near future bug alert!!!
+    _ => 0 as f32, //Return 0 if unknown operation. Near future bug alert!!!
   };
 }
 
diff --git a/Enum-and-Match-Systems-in-Rust/index.html b/Enum-and-Match-Systems-in-Rust/index.html index 7c14773..e6efe6e 100644 --- a/Enum-and-Match-Systems-in-Rust/index.html +++ b/Enum-and-Match-Systems-in-Rust/index.html @@ -114,10 +114,10 @@

Enum and Match Systems in Rust

} fn compute_results() -> FunctionStatus { - // Successful execution would look like the following: - // return FunctionStatus::PASS("Everything looks good".to_string()); + // Successful execution would look like the following: + // return FunctionStatus::PASS("Everything looks good".to_string()); - // While a failure would be indicated as follows: + // While a failure would be indicated as follows: return FunctionStatus::FAILURE(SeverityStatus::FATAL("Continuing beyond this point will cause more damage to the hardware".to_string())); }
@@ -128,18 +128,18 @@

Enum and Match Systems in Rust

let res = compute_results(); match res { FunctionStatus::PASS(x) => { - // Handling a PASS response + // Handling a PASS response println!("PASS: {}", x); } FunctionStatus::FAILURE(x) => { - // Handling a FAILURE response + // Handling a FAILURE response match x { SeverityStatus::BENIGN(y) => { - // Handling a BENIGN FAILURE response + // Handling a BENIGN FAILURE response println!("BENIGN: {}", y); } SeverityStatus::FATAL(y) => { - // Handling a FATAL FAILURE response + // Handling a FATAL FAILURE response println!("FATAL: {}", y); } }; @@ -165,8 +165,8 @@

Enum and Match Systems in Rust

} }; } - _ => { - // Here goes the handling of "everything else", or it can be left out completely + _ => { + // Here goes the handling of "everything else", or it can be left out completely } }; } @@ -184,15 +184,15 @@

Enum and Match Systems in Rust

SeverityStatus::FATAL(message) => { println!("FATAL: {}", message); } - SeverityStatus::BENIGN(_) => { - // Leaving this case unhandled - // NOTE: you can't print _. If you change your mind and decide to - // actually handle this case, replace `_` with a valid variable name. + SeverityStatus::BENIGN(_) => { + // Leaving this case unhandled + // NOTE: you can't print _. If you change your mind and decide to + // actually handle this case, replace `_` with a valid variable name. } }; } - FunctionStatus::PASS(_) => { - // Leaving this case unhandled + FunctionStatus::PASS(_) => { + // Leaving this case unhandled } }; } diff --git a/Generic-Types-in-Strongly-Typed-Languages/index.html b/Generic-Types-in-Strongly-Typed-Languages/index.html index 09937bf..18f91cf 100644 --- a/Generic-Types-in-Strongly-Typed-Languages/index.html +++ b/Generic-Types-in-Strongly-Typed-Languages/index.html @@ -68,74 +68,74 @@

Introduction to Generic Types

Let’s start with an example, a common pattern for JavaScript developers is to copy JSON objects using JSON.stringify and JSON.parse, like this:

-
function copyObject (obj) {
-    const string = JSON.stringify(obj);
-    const theCopy = JSON.parse(string);
+
function copyObject (obj) {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
     return theCopy;
 }
 

The parameter obj in the above example can be anything, it can be a number, a string, an array, object literal …etc. So adding type definitions might be quite useless (without generic types):

-
function copyObject (obj: any): any {
-    const string = JSON.stringify(obj);
-    const theCopy = JSON.parse(string);
+
function copyObject (obj: any): any {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
     return theCopy;
 }
 

But with generic types, our function becomes as strongly typed as any function can be:

-
function copyObject<T>(obj: T): T {
-    const string = JSON.stringify(obj);
-    const theCopy = JSON.parse(string);
+
function copyObject<T>(obj: T): T {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
     return theCopy;
 }
 
 const myObject = { a: 0, b: 3 };
 
-const theCopy = copyObject(myObject);
+const theCopy = copyObject(myObject);
 
-console.log(theCopy.a); // OK!
-console.log(theCopy.b); // OK!
-console.log(theCopy.c); // Compile Error!
+console.log(theCopy.a); // OK!
+console.log(theCopy.b); // OK!
+console.log(theCopy.c); // Compile Error!
 

The syntax for writing generic types is like many languages, before the parameters using the angle brackets.

Another example of how you can make use of generic types is when requesting data from a server.

-
function getFromServer<DataSchema>(url: string): Data {
+
function getFromServer<DataSchema>(url: string): Data {
     // make the request
     // and return the data
 }
 
 interface Employees {
-    departmentA: string[];
-    departmentB: string[];
+    departmentA: string[];
+    departmentB: string[];
 };
 
 const employees = getFromServer<Employees>("http://www.example.com/api/employees.json");
 
-console.log(employees.departmentA); // OK!
-console.log(employees.departmentB); // OK!
-console.log(employees.departmentC); // Compile error!
-console.log(employees.departmentA.length) // OK!
-console.log(employees.departmentA + employees.departmentB);
+console.log(employees.departmentA); // OK!
+console.log(employees.departmentB); // OK!
+console.log(employees.departmentC); // Compile error!
+console.log(employees.departmentA.length) // OK!
+console.log(employees.departmentA + employees.departmentB);
 // ^ Compile errors because they are arrays
 

The previous example shows how generic types are treated like additional arguments in the function. And that’s what they really are, additional arguments. In the first example, however, TypeScript was smart enough to determine the type of the passed value, and we did not need to pass any generic type values in angle brackets. Typescript can also be smart and notify you when you do something like this:

-
function copyObject<T>(obj: T): T {
-    const string = JSON.stringify(obj);
-    const theCopy = JSON.parse(string);
+
function copyObject<T>(obj: T): T {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
     return theCopy;
 }
 
 const myObject = { a: 0, b: 3 };
 
-const theCopy = copyObject<number>(myObject);
+const theCopy = copyObject<number>(myObject);
 // ^ Compile Error:
 // Argument of type '{ a: number; b: number; }'
 // is not assignable to parameter of type 'number'.
@@ -146,8 +146,8 @@ 

Introduction to Generic Types

So, in the types directory, you can have this file interface.employee.ts

export interface Employee {
-    name: string;
-    birth: number;
+    name: string;
+    birth: number;
 }
 
@@ -169,63 +169,63 @@

Restricting Generic Types

You can also restrict how generic your generic types can be, for example, let’s say that we have a function that logs the length of the passed value (whatever it is):

-
function logLength (val) {
-    console.log(val.length);
+
function logLength (val) {
+    console.log(val.length);
 }
 

But there are only two built-in types in javascript that have the length property, String and Array. So what we can do is set a constraint on the generic type like this:

interface hasLength {
-    length: number;
+    length: number;
 }
 
-function logLength <T extends hasLength> (val: T) {
-    console.log(val.length);
+function logLength <T extends hasLength> (val: T) {
+    console.log(val.length);
 }
 
-logLength("string"); // OK
-logLength(["a","b","c"]); // OK
-logLength({
+logLength("string"); // OK
+logLength(["a","b","c"]); // OK
+logLength({
     width: 300,
     length: 600
 }); // Also OK because it has the length property
-logLength(17); // Compile Error!
+logLength(17); // Compile Error!
 

Index Types With Generic Types

A more elaborate example is a function that copies (Using JSON.stringify and JSON.parse) a property of any object that it receives.

-
function copyProperty<OBJ, KEY extends keyof OBJ>(obj: OBJ, key: KEY): OBJ[KEY] {
-    const string = JSON.stringify(obj[key]);
-    const copied = JSON.parse(string);
+
function copyProperty<OBJ, KEY extends keyof OBJ>(obj: OBJ, key: KEY): OBJ[KEY] {
+    const string = JSON.stringify(obj[key]);
+    const copied = JSON.parse(string);
     return copied;
 }
 
 const car = { engine: "v8", milage: 123000, color: "red" };
 const animal = { name: "Domestic Cat", species: "silvestris" };
 
-copyProperty(car, "engine"); // OK
-copyProperty(car, "color").length; // OK
-copyProperty(car, "milage").length; // Compile error, because it's a number!
-copyProperty(animal, "color"); // Compile error, because "color" is not a property on that object!
+copyProperty(car, "engine"); // OK
+copyProperty(car, "color").length; // OK
+copyProperty(car, "milage").length; // Compile error, because it's a number!
+copyProperty(animal, "color"); // Compile error, because "color" is not a property on that object!
 // so you can only pass the object's property names and
 // typescript will be smart enough to determine their values
 

Now let’s step it up a bit, by making our copyProperty able to copy multiple properties on the same call, so the second argument, will be an array of property names that will be copied and returned as an array.

-
function copyProperties<OBJ, KEY extends keyof OBJ>(obj: OBJ, keys: Array<KEY>): Array<OBJ[KEY]> {
+
function copyProperties<OBJ, KEY extends keyof OBJ>(obj: OBJ, keys: Array<KEY>): Array<OBJ[KEY]> {
 	return keys
-		.map(x => JSON.stringify(obj[x]))
-		.map(x => JSON.parse(x))
+		.map(x => JSON.stringify(obj[x]))
+		.map(x => JSON.parse(x))
 }
 
 const car = { engine: "v8", milage: 123000, color: "red" };
 
-const a: string[] = copyProperties(car, ["engine", "color"]); // OK
-const b: string[] = copyProperties(car, ["engine", "milage"]);
+const a: string[] = copyProperties(car, ["engine", "color"]); // OK
+const b: string[] = copyProperties(car, ["engine", "milage"]);
 // ^ Compile Error! because one of the array values is a number
 // and that's because one of the properties
 // we're copying is "milage".
@@ -248,14 +248,14 @@ 

Mapped Generic Types

// this is a generic type, it takes any type (object) // as an argument and returns the same type // but with every property being optional -type Partial<T> = { - [P in keyof T]?: T[P] +type Partial<T> = { + [P in keyof T]?: T[P] } -function copyAndModify<T>(obj: T, mods:Partial<T>): T { - const string = JSON.stringify(obj); - const copy = JSON.parse(string); - Object.keys(mods).forEach(key => { +function copyAndModify<T>(obj: T, mods:Partial<T>): T { + const string = JSON.stringify(obj); + const copy = JSON.parse(string); + Object.keys(mods).forEach(key => { copy[key] = mods[key]; }); return copy; @@ -269,15 +269,15 @@

Mapped Generic Types

}; -copyAndModify(doc, { createdAt: new Date().getTime() }) // OK -copyAndModify(doc, { title: "New title" }) // OK -copyAndModify(doc, { content: 0 }) +copyAndModify(doc, { createdAt: new Date().getTime() }) // OK +copyAndModify(doc, { title: "New title" }) // OK +copyAndModify(doc, { content: 0 }) // Compile Error! // Because content is a string, so we must // put a string when modifying it -copyAndModify(doc, { author: "Some one" }) +copyAndModify(doc, { author: "Some one" }) // Compile Error! // Because we did not have the property author on the original document diff --git a/My-Thoughts-on-TypeScript/index.html b/My-Thoughts-on-TypeScript/index.html index 578b0ca..201e2c2 100644 --- a/My-Thoughts-on-TypeScript/index.html +++ b/My-Thoughts-on-TypeScript/index.html @@ -62,14 +62,14 @@

Type checking is mo

You might ask: why would anyone spend their time and energy writing:

-
function add (a: number, b: number): number {
+
function add (a: number, b: number): number {
 	return a + b;
 }
 

Instead of:

-
function add (a, b) {
+
function add (a, b) {
 	return a + b;
 }
 
@@ -93,7 +93,7 @@

Reduced bugs and compile time erro
let a = 1;
 let b = "string";
-add(a, b);
+add(a, b);
 

In javascript, the aforementioned code will act like nothing is wrong and would just return "1string", i.e. It will fail silently, not even a runtime error will be produced. Which is the last thing you would want.

@@ -111,17 +111,17 @@

Reduced bugs and compile time erro

Have a look at this code for instance:


-function getAuthorLines(text) {
-	return text.match(/^author: (.*)$/gmi);
+function getAuthorLines(text) {
+	return text.match(/^author: (.*)$/gmi);
 }
 
-function getAuthorNames(lines) {
-	return lines.map((line)=>line.substr(8))
+function getAuthorNames(lines) {
+	return lines.map((line)=>line.substr(8))
 }
 
 let text = "Paper title: TypeScript for the Win\nAuthor: Alex Corvi\nAuthor: John Doe\nAuthor: Jane Doe\n";
 
-console.log(getAuthorNames(getAuthorLines(text)));
+console.log(getAuthorNames(getAuthorLines(text)));
 
 
@@ -136,7 +136,7 @@

Reduced bugs and compile time erro

Now add the following line:

-
console.log(getAuthorNames(getAuthorLines(text.substr(0,30))));
+
console.log(getAuthorNames(getAuthorLines(text.substr(0,30))));
 

Ouch! That’s a runtime error! That’s because String.match doesn’t always return an array, it might return null.

@@ -144,21 +144,21 @@

Reduced bugs and compile time erro

Here’s another code, can you spot what’s wrong?

var theThing = null;
-var replaceThing = function () {
+var replaceThing = function () {
 	var priorThing = theThing;
-	var unused = function () {
-		if (priorThing) {
-			console.log("hi");
+	var unused = function () {
+		if (priorThing) {
+			console.log("hi");
 		}
 	};
 	theThing = {
-		longStr: new Array(1000000).join('*'),
-		someMethod: function () {
-			console.log("abc");
+		longStr: new Array(1000000).join('*'),
+		someMethod: function () {
+			console.log("abc");
 		}
 	};
 };
-setInterval(replaceThing, 1000);
+setInterval(replaceThing, 1000);
 

That was a classic example of how you can cause memory leaks in JavaScript. This one leaks 1 MegaByte per second. In TypeScript, You can’t reassign the theThing variable from null to Object.

@@ -220,41 +220,41 @@

Enough talk, show me the code

I can easily bet that all javascript developers will be able to understand the following piece of code:


-let x: number = 1;
-let y: number = 500;
+let x: number = 1;
+let y: number = 500;
 
-function getRand (min: number, max: number): number {
-	return Math.floor(Math.random() * (max - min)) + min;
+function getRand (min: number, max: number): number {
+	return Math.floor(Math.random() * (max - min)) + min;
 }
 
-console.log(getRand(x, y));
+console.log(getRand(x, y));
 
 

So is this:


-class House {
-	address: string;
-	bedrooms: number;
-	area: number;
+class House {
+	address: string;
+	bedrooms: number;
+	area: number;
 	safeNeighborhood:boolean;
 	goodCondition:boolean;
-	private priceCoefficient: number = 65;
-	get price(): number {
-		return ((this.bedrooms * this.area) +
+	private priceCoefficient: number = 65;
+	get price(): number {
+		return ((this.bedrooms * this.area) +
 			(this.safeNeighborhood ? 1000 : 0 ) +
 			(this.goodCondition ? 1000 : 0 )) * this.priceCoefficient;
 	}
 }
 
-let myHouse = new House();
+let myHouse = new House();
 myHouse.bedrooms = 4;
 myHouse.area = 300;
 myHouse.safeNeighborhood = true;
 myHouse.goodCondition = true;
 
-console.log(myHouse.price)
+console.log(myHouse.price)
 
 
@@ -266,7 +266,7 @@

Interfaces

You can write your object type definition like this:

-
let myObj: { a: number; str: string; } = {
+
let myObj: { a: number; str: string; } = {
 	a: 123,
 	str: "my string"
 }
@@ -275,8 +275,8 @@ 

Interfaces

Or you can declare a re-usable interface:

interface MyObj {
-	a: number;
-	str: string;
+	a: number;
+	str: string;
 }
 
 let myObj1: MyObj = {
@@ -297,22 +297,22 @@ 

Compilation

After type-checking, the compiler will emit very clean and readable code. So this:

-
let x: number = 1;
-let y: number = 500;
-function getRand (min: number, max: number): number {
-	return Math.floor(Math.random() * (max - min)) + min;
+
let x: number = 1;
+let y: number = 500;
+function getRand (min: number, max: number): number {
+	return Math.floor(Math.random() * (max - min)) + min;
 }
-console.log(getRand(x, y));
+console.log(getRand(x, y));
 

Will compile to this:

var x = 1;
 var y = 500;
-function getRand(min, max) {
-	return Math.floor(Math.random() * (max - min)) + min;
+function getRand(min, max) {
+	return Math.floor(Math.random() * (max - min)) + min;
 }
-console.log(getRand(x, y));
+console.log(getRand(x, y));
 

Have a look at the TypeScript Playground where you can compile TypeScript immediately in your browser. Yes, it’s being compiled in the browser. This is possible since the TypeScript compiler is written in TypeScript.

@@ -339,18 +339,18 @@

Type inference

let str = "string"; // inferred as a string // function return type will also be inferred -function add (a:number, b:number) { +function add (a:number, b:number) { return a + b; } -let b = add(1, 3); // type inferred as a number -let x = add(c, b); // compiler will produce an error +let b = add(1, 3); // type inferred as a number +let x = add(c, b); // compiler will produce an error

Another advanced example:

// Notice how we won't declare any types:
-function myFunc (param) {
+function myFunc (param) {
 	return {
 		n: 0,
 		str: "myString",
@@ -364,7 +364,7 @@ 

Type inference

} } // hover over someVal -myFunc(10).obj.obj.obj.someVal +myFunc(10).obj.obj.obj.someVal

Now when hovering over someVal you’ll notice that it’s type is declared as:

@@ -414,7 +414,7 @@

Example: Consuming Express in T
// import
 import { Request, Response, NextFunction } from "@types/express";
 // declare
-function myMiddleWare (req: Request, res: Response, next:NextFunction) {
+function myMiddleWare (req: Request, res: Response, next:NextFunction) {
 	// middleware code
 }
 
diff --git a/Rust-for-High-Level-Programming-Language-Developers/index.html b/Rust-for-High-Level-Programming-Language-Developers/index.html index f028abf..65176bb 100644 --- a/Rust-for-High-Level-Programming-Language-Developers/index.html +++ b/Rust-for-High-Level-Programming-Language-Developers/index.html @@ -71,7 +71,7 @@

The short answer i

Here’s how you’d write this in Rust:

-
// Our pseudo-JSON object skeleton
+
// Our pseudo-JSON object skeleton
 struct Person {
   full_name: String,
   date_of_birth: String,
@@ -111,9 +111,9 @@ 

Sure, forward we go

} struct DateOfBirth { - day: i8, // 8-bit integer variable + day: i8, // 8-bit integer variable month: i8, - year: i16 // 16-bit integer variable + year: i16 // 16-bit integer variable } enum Gender { @@ -146,9 +146,9 @@

Sure, forward we go

Our pseudo-JSON object is now looking much cleaner and even easier to utilize. Speaking of utilization, how do we reference our fields? Well, you’ve probably guessed it already. Yes, it’s the dot operator. If you’re interested in, say, printing the full name of your Person object, here’s how you’d do that:

-
// The following line of code goes inside your main function right after
-// your person object has been instantiated, or really anywhere after the
-// object has been declared.
+
// The following line of code goes inside your main function right after
+// your person object has been instantiated, or really anywhere after the
+// object has been declared.
 
 println!("{} {}", person.full_name.first_name, person.full_name.last_name);
 
@@ -194,9 +194,9 @@

Sure, forward we go

#[derive(Debug)] struct DateOfBirth { - day: i8, // 8-bit integer variable + day: i8, // 8-bit integer variable month: i8, - year: i16 // 16-bit integer variable + year: i16 // 16-bit integer variable } #[derive(Debug)] @@ -241,13 +241,13 @@

Sure, forward we go

Say you have a Person class with a constructor that takes a first_name and a last_name and provides two separate getter functions that give you these two string values whenever you need them. You’d write your class something as follows:

class Person:
-  def __init__(self, firstName, lastName):
-    self.firstName = firstName
-    self.lastName = lastName
-  def getFirstName(self):
-    return self.firstName
-  def getLastName(self):
-    return self.lastName
+  def __init__(self, firstName, lastName):
+    self.firstName = firstName
+    self.lastName = lastName
+  def getFirstName(self):
+    return self.firstName
+  def getLastName(self):
+    return self.lastName
 

Notice how we have our fields and functions mixed together inside a single class. Rust separates the two. You’d have your fields defined inside a struct and an impl containing all relevant functions. So, when interpreted, our Python class would look in Rust as follows:

@@ -310,8 +310,8 @@

Drop trait to our object and see when Drop is invoked:

-
impl Drop for Response {
-  fn drop (&mut self) {
+
impl Drop for Response {
+  fn drop (&mut self) {
     println!("I ran out of scope. I'm about to be destroyed")
   }
 }
@@ -324,8 +324,8 @@ 

message: String } -impl Drop for Response { - fn drop (&mut self) { +impl Drop for Response { + fn drop (&mut self) { println!("I ran out of scope. I'm about to be destroyed") } } @@ -347,30 +347,30 @@

+, -, *, /, %, etc). A vector class with + overloaded would look something like the following:

class Vector:
-  def __init__(self, a, b):
-    self.a = a
-    self.b = b
-  def __add__(self, otherVector):
-    return Vector(self.a + otherVector.a, self.b + otherVector.b)
-  def __str__(self):
-    return "Vector(%s, %s)" % (self.a, self.b)
+  def __init__(self, a, b):
+    self.a = a
+    self.b = b
+  def __add__(self, otherVector):
+    return Vector(self.a + otherVector.a, self.b + otherVector.b)
+  def __str__(self):
+    return "Vector(%s, %s)" % (self.a, self.b)
 

And if you were to add two Vector objects together, you’d so something like the following:

-
v1 = Vector(1, 2)
-v2 = Vector(5, 7)
+
v1 = Vector(1, 2)
+v2 = Vector(5, 7)
 v3 = v1 + v2
 

And print the result as follows:

-
print(v3)
+
print(v3)
 

This will print the following:

-
Vector(6, 9)
+
Vector(6, 9)
 

Hmm.. Let’s see how we could go about implementing this in Rust. First, we’d need to somehow find a way to add objects (i.e., overload the + operator). Second, we’d need to be able to give our object to println and see it print something like Vector(#, #). Lucky for us, both of these features are available as traits we can implement. Let’s chase them one at a time. We’ll start with the Add trait.

@@ -419,9 +419,9 @@

use std::fmt::{Debug, Formatter, Result};
+
use std::fmt::{Debug, Formatter, Result};
 impl Debug for Vector {
-  fn fmt(&self, f: &mut Formatter) -> Result {
+  fn fmt(&self, f: &mut Formatter) -> Result {
     return write!(f, "Vector({}, {})", self.a, self.b);
   }
 }
@@ -464,9 +464,9 @@ 

} } -use std::fmt::{Debug, Formatter, Result}; +use std::fmt::{Debug, Formatter, Result}; impl Debug for Vector { - fn fmt(&self, f: &mut Formatter) -> Result { + fn fmt(&self, f: &mut Formatter) -> Result { return write!(f, "Vector({}, {})", self.a, self.b); } } @@ -483,12 +483,12 @@

use std::fmt::{Debug, Formatter, Result};
+
use std::fmt::{Debug, Formatter, Result};
 

With:

-
use std::fmt::{Display, Formatter, Result};
+
use std::fmt::{Display, Formatter, Result};
 

And:

@@ -600,14 +600,14 @@

Functions

What if you want to pass the string to the function instead of hard-coding a specific value? Then, you’d write it like this:

fn greeting (message: String) {
-    // TODO: Implement me
+    // TODO: Implement me
 }
 

Multiple function arguments? Sure! Here’s how:

fn greeting (name: String, message: String) {
-    // TODO: Implement me
+    // TODO: Implement me
 }
 
@@ -660,16 +660,16 @@

Function Pointers

If you’re coming from a solid background in languages like C and C++, chances are you’ve worked with function pointers a lot. You’ve probably even worked with function pointers in languages like JavaScript and Python without ever coming across the name. At its core, a function pointer is a variable holding access to a specific memory location representing the beginning of the function. In JavaScript, if you were to have the following:

-
function callee () {
+
function callee () {
   // TODO: Implement me
 }
 
-function caller (callback) {
+function caller (callback) {
   // TODO: Implement a task
-  callback();
+  callback();
 }
 
-caller(callback);
+caller(callback);
 

It can be said that “caller is a function that takes an argument of type function pointer (which in this case is our callee function)”.

@@ -687,7 +687,7 @@

Function Pointers

Here we’re telling the compiler to expect our function pointer to have no arguments and return an 8-bit integer. Let’s now define a function according to these specifications:

fn ls () -> i8 {
-	// TODO: Implement me
+	// TODO: Implement me
 	return 0;
 }
 
@@ -700,7 +700,7 @@

Function Pointers

let cmd = CommandInterface {
 	str: "ls".to_string(),
-	exec: ls // points to the ls function declared above
+	exec: ls // points to the ls function declared above
 };
 
 (cmd.exec)();
@@ -744,10 +744,10 @@ 

Conditionals

The following JavaScript code:

-
if (x == 0 || x == 2) {
+
if (x == 0 || x == 2) {
 	// TODO: Implement me
 }
-else if (x == 1) {
+else if (x == 1) {
 	// TODO: Implement me
 }
 else {
@@ -758,13 +758,13 @@ 

Conditionals

is written in Rust as follows:

if x == 0 || x == 2 {
-	// TODO: Implement me
+	// TODO: Implement me
 }
 else if x == 1 {
-	// TODO: Implement me
+	// TODO: Implement me
 }
 else {
-	// TODO: Implement me
+	// TODO: Implement me
 }
 
@@ -785,21 +785,21 @@

Conditionals

Matching (aka pseudo-Switch-Case Statements)

Matching is your typical switch case code block plus the ability to return something. If you were to compare integer x against a number of different values, using classical if - else -- else if gets pretty tedious really quickly, so developers tend to resort to switch case statements. Referring back to our x example, the following JavaScript compares x against 5 different values (cases):

-
switch (x) {
+
switch (x) {
   case 1:
-    console.log('x is 1');
+    console.log('x is 1');
     break;
   case 2:
-    console.log('x is 2');
+    console.log('x is 2');
     break;
   case 3:
-    console.log('x is 3');
+    console.log('x is 3');
     break;
   case 4:
-    console.log('x is 4');
+    console.log('x is 4');
     break;
   default:
-    console.log('x is something else');
+    console.log('x is something else');
     break;
 }
 
@@ -812,7 +812,7 @@

Matching (aka pseudo-Switch- 3 => println!("x is 3"), 4 => println!("x is 4"), 5 => println!("x is 5"), - _ => println!("x is something else") + _ => println!("x is something else") };

@@ -828,7 +828,7 @@

Matching (aka pseudo-Switch- 3 => "x is 3", 4 => "x is 4", 5 => "x is 5", - _ => "x is something else" + _ => "x is something else" }; println!("{}", res);

@@ -842,20 +842,20 @@

Loops

The for loop is used when you’ve already decided the number of times you’d like to iterate. For example, the following will loop 9 times and print the values 0 through 9:

-
for i in 0..10 {
+
for i in 0..10 {
     println!("{}", i);
 }
 

This interprets to the following Python code:

-
for i in range(0, 10):
-    print("%d" % i)
+
for i in range(0, 10):
+    print("%d" % i)
 

You can also iterate over a list using a for loop as follows:

-
for i in &[10, 20, 30] {
+
for i in &[10, 20, 30] {
     println!("{}", i);
 }
 
@@ -863,13 +863,13 @@

Loops

This is equivalent to the following Python code:

for i in [10, 20, 30]:
-    print("%d" % i)
+    print("%d" % i)
 

for loops can also preform some sophisticated tasks. For instance, if you have the string "hello\nworld\nmy\nname\nis\nFadi" and you want it up split it up using the linefeed (\n) delimiter, you can use the lines() function. This function returns an enumerator containing both the substring and the line number. So something like the following:

let my_str_tokens = "hello\nworld\nmy\nname\nis\nFadi".lines();
-for (line_no, term) in my_str_tokens.enumerate() {
+for (line_no, term) in my_str_tokens.enumerate() {
     println!("{}: {}", line_no, term);
 }
 
@@ -886,15 +886,15 @@

Loops

The above example is equivalent to the following Python code:

-
myStrTokens = "hello\nworld\nmy\nname\nis\nFadi".split("\n")
-for i in range(0, len(myStrTokens)):
-    print("%d: %s" % (i, myStrTokens[i]))
+
myStrTokens = "hello\nworld\nmy\nname\nis\nFadi".split("\n")
+for i in range(0, len(myStrTokens)):
+    print("%d: %s" % (i, myStrTokens[i]))
 

The while loop is used when you’re not sure how many times you need to loop. It works the exact same way a while loop works in languages like C, C++, C#, Java, JavaScript, and Python. Here’s a JavaScript example:

bool status = true;
-while (status) {
+while (status) {
   // add some case that can set `status` to false
 }
 
@@ -903,7 +903,7 @@

Loops

let status: bool = true;
 while status {
-  // add some case that can set `status` to false
+  // add some case that can set `status` to false
 }
 
@@ -912,14 +912,14 @@

Loops

let status: bool = true;
 
 while true {
-  // add some case that can set `status` to false
+  // add some case that can set `status` to false
 }
 

When you could actually have this:

loop {
-  // add some case that can break out of the loop
+  // add some case that can break out of the loop
 }
 
diff --git a/about/index.html b/about/index.html index c1340f2..b5a749d 100644 --- a/about/index.html +++ b/about/index.html @@ -9,10 +9,8 @@ - - + + @@ -83,7 +81,7 @@

IQDevs

About

-

IQDevs is a Facebook group of technical enthusiasts holding skills from various technical backgrounds spanning all over the globe. From the U.S. to Europe to the Middle East, people who share a homeland and a passion for skill enhancement, sharing ideas and following bleeding edge technical trends. We focus to upgrade our knowledge and our limit is the sky.

+

IQDevs is a Facebook community of technical enthusiasts with diverse skill sets and backgrounds from around the world, including the United States, Europe, and the Middle East. Our members share a common passion for continuous learning, exchanging ideas, and staying on top of cutting-edge trends in their respective fields. Our focus is on pushing the boundaries of our knowledge, and we believe that the sky is the only limit to our potential.

diff --git a/feed.xml b/feed.xml index 2fa8007..0859bce 100644 --- a/feed.xml +++ b/feed.xml @@ -1,2376 +1,2376 @@ -Jekyll2020-06-01T18:54:17+00:00/feed.xmlIQDevsTechnology Excellence RedefinedZGPS - Achieving Abstraction with Golang2020-05-30T05:00:00+00:002020-05-30T05:00:00+00:00/ZGPS%20-%20Achieving%20Abstraction%20with%20Golang<p>One of the early design challenges we faced when designing the <code class="language-plaintext highlighter-rouge">DSP</code> (Device Service Provider) project is coming up with a plug-and-play architecture. <code class="language-plaintext highlighter-rouge">DSP</code>’s main responsibility is to read data from a specific tracking device, process and store the data, or send commands and process responses. Different devices come with different protocols, though they share common traits, like they all (all the ones we now support at least) are TCP based. Devices, when connected to <code class="language-plaintext highlighter-rouge">DSP</code>, are expected to be recognized so they’re handed to the proper protocol handler. Our silver bullet here is abstraction, but then we’re using Go, and Go doesn’t have native support for abstractions. So how do we solve this?</p> - -<p>We came up with a list of functions every device –no matter how distinct– must support, and we created an interface called <code class="language-plaintext highlighter-rouge">DeviceProtocol</code> that encompasses all these functions. Our interface will include functions like <code class="language-plaintext highlighter-rouge">SetDeviceConnection</code>, <code class="language-plaintext highlighter-rouge">SetLogger</code>, <code class="language-plaintext highlighter-rouge">Read</code>, <code class="language-plaintext highlighter-rouge">Write</code>, <code class="language-plaintext highlighter-rouge">GetIMEI</code>, <code class="language-plaintext highlighter-rouge">SetUnit</code>, <code class="language-plaintext highlighter-rouge">Acknowledge</code>, <code class="language-plaintext highlighter-rouge">Reject</code>, <code class="language-plaintext highlighter-rouge">Handle</code>, <code class="language-plaintext highlighter-rouge">StoreRecord</code>, and <code class="language-plaintext highlighter-rouge">Disconnect</code>.</p> - -<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="c">// DeviceProtocol is a set of functions all supports protocols need to implement.</span> -<span class="k">type</span> <span class="n">DeviceProtocol</span> <span class="k">interface</span> <span class="p">{</span> - <span class="c">// SetDeviceConnection is called to hand the connection over to the device</span> - <span class="c">// protocol instance. This is the first thing that happens once a new</span> - <span class="c">// device is connected.</span> - <span class="n">SetDeviceConnection</span><span class="p">(</span><span class="n">net</span><span class="o">.</span><span class="n">Conn</span><span class="p">)</span> - - <span class="c">// SetLogger keeps a copy of a provided Logger for the protocol to consume.</span> - <span class="n">SetLogger</span><span class="p">(</span><span class="n">logger</span><span class="o">.</span><span class="n">Logger</span><span class="p">)</span> - - <span class="c">// Read allows the protocol to read a specified number of bytes directly</span> - <span class="c">// from the device. Refer to the ReadParameters structure to find out</span> - <span class="c">// and/or alter the capabilities of the Read function.</span> - <span class="n">Read</span><span class="p">(</span><span class="n">ReadParameters</span><span class="p">)</span> <span class="p">(</span><span class="n">Buffer</span><span class="p">,</span> <span class="kt">error</span><span class="p">)</span> - - <span class="c">// Write allows the protocol to send byte streams directly to the device.</span> - <span class="c">// If the number of bytes written does NOT comport with the number of bytes</span> - <span class="c">// in the slice passed to the function, an error is returned.</span> - <span class="n">Write</span><span class="p">([]</span><span class="kt">byte</span><span class="p">)</span> <span class="kt">error</span> - - <span class="c">// GetIMEI does what is necessary for the protocol to retrieve the IMEI from</span> - <span class="c">// the device. Failures can be expected, and tend to be more occasional, then</span> - <span class="c">// they need to be, so the caller needs to always watch out for errors. That</span> - <span class="c">// is, if `error` is anything other than nil, the proper action is to reject</span> - <span class="c">// the connection and bailout.</span> - <span class="n">GetIMEI</span><span class="p">()</span> <span class="p">(</span><span class="kt">int64</span><span class="p">,</span> <span class="kt">error</span><span class="p">)</span> - - <span class="c">// Acknowledge is automatically called once an IMEI is retrieved and</span> - <span class="c">// authenticated.</span> - <span class="c">// NOTE: Units that are marked off as disabled in the database won't</span> - <span class="c">// be acknowledged.</span> - <span class="n">Acknowledge</span><span class="p">()</span> <span class="kt">error</span> - - <span class="c">// Reject is automatically called if the device fails to send an IMEI</span> - <span class="c">// within a specified period of time, or if the IMEI is not found in</span> - <span class="c">// the database or if the database object is marked off as disabled.</span> - <span class="c">// This function is automatically called right before Disconnect is.</span> - <span class="n">Reject</span><span class="p">()</span> <span class="kt">error</span> - - <span class="c">// SetUnit is called once a device is acknowledged. The point of this</span> - <span class="c">// call is to hand over the Unit object to the protocol so that the</span> - <span class="c">// protocol is capable of inferring the Unit identifier.</span> - <span class="n">SetUnit</span><span class="p">(</span><span class="n">ms</span><span class="o">.</span><span class="n">Unit</span><span class="p">)</span> - - <span class="c">// Handle is the entry point to a device handler. Every supported protocol</span> - <span class="c">// needs to implement this function. &lt;b&gt;No abstraction version of this</span> - <span class="c">// function is provided&lt;/b&gt; for the sole reason that different devices</span> - <span class="c">// come with different protocols.</span> - <span class="n">Handle</span><span class="p">()</span> <span class="kt">error</span> - - <span class="c">// StoreRecord is responsible for processing one device Record at a time.</span> - <span class="c">// Record (defined in Record.go) is supposed to at least have a Unit</span> - <span class="c">// object (defined in ms/Unit.go) and a Position object (defined in</span> - <span class="c">// ms/Position.go). Whether the Position is valid or not is decided by</span> - <span class="c">// its own microservice later.</span> - <span class="n">StoreRecord</span><span class="p">(</span><span class="o">*</span><span class="n">Record</span><span class="p">)</span> <span class="kt">error</span> - - <span class="c">// Disconnect is the last function called towards the end of the lifecycle</span> - <span class="c">// of a protocol instance. That is, the function is called before the</span> - <span class="c">// protocol instance is dismissed forever. Protocol lifecycle comes to an</span> - <span class="c">// end when the device has been idle (no data received from a device within a</span> - <span class="c">// designated timeframe), or if the device fails to send an IMEI or if the</span> - <span class="c">// device IMEI is not associated with any Unit objects in the database, or</span> - <span class="c">// if the Unit object is marked as disabled.</span> - <span class="n">Disconnect</span><span class="p">()</span> <span class="kt">error</span> -<span class="p">}</span> -</code></pre></div></div> - -<p>Soon after a tracking device connects, we call <code class="language-plaintext highlighter-rouge">SetDeviceConnection</code> with our connection object, we then call <code class="language-plaintext highlighter-rouge">GetIMEI</code> that’ll internally compose a device identifier request and send it to the device using the <code class="language-plaintext highlighter-rouge">Write</code> function. The response is then retrieved with the <code class="language-plaintext highlighter-rouge">Read</code> function. Our <code class="language-plaintext highlighter-rouge">GetIMEI</code> function returns either the device unique identifier or an error (happens when the client fails to provide its IMEI within a designated timeframe, or when invalid data is provided or when the function identifies a suspicious activity).</p> - -<p>A lot of these functions will have identical internal implementations. For instance,</p> -<ul> - <li><code class="language-plaintext highlighter-rouge">SetDeviceConnection</code>, <code class="language-plaintext highlighter-rouge">SetLogger</code> and <code class="language-plaintext highlighter-rouge">SetUnit</code> are a common one-liner across all protocol implementations.</li> - <li><code class="language-plaintext highlighter-rouge">Read</code> and <code class="language-plaintext highlighter-rouge">Write</code> will be identical across all protocols given Read is flexible with its <code class="language-plaintext highlighter-rouge">ReadParameters</code> and Write blindlessly transmits a given slice of bites. No device-specific intelligence required.</li> - <li><code class="language-plaintext highlighter-rouge">StoreRecord</code> is a device-agnostic microservice-consuming function that doesn’t need to be reimplemented for every protocol.</li> - <li><code class="language-plaintext highlighter-rouge">Disconnect</code> performs some Record-related actions (device-agnostic, remember?) and closes the TCP connection generically.</li> -</ul> - -<p>The way around the issue is to have a form of abstraction that allows protocols to adopt at will and override when needed. Problem is Go isn’t an OOP language (that’s not to say OOP can’t be employed in the language), and so class abstraction isn’t a first-class construct of the language. What we do here is we create a <code class="language-plaintext highlighter-rouge">DeviceProtocolHeader</code> with our common functions defined and implemented, and aggregate the object in every protocol object we create:</p> - -<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="c">// DeviceProtocolHeader has a set of abstract functions that device protocols tend to have</span> -<span class="c">// in common. Instead of having to re-implement the same errorprocedures for every</span> -<span class="c">// Protocol implementation, it is recommended to include this header and have</span> -<span class="c">// the extra functionality at no cost.</span> -<span class="k">type</span> <span class="n">DeviceProtocolHeader</span> <span class="k">struct</span> <span class="p">{</span> - <span class="n">logger</span><span class="o">.</span><span class="n">Logger</span> - <span class="n">client</span> <span class="n">net</span><span class="o">.</span><span class="n">Conn</span> - <span class="n">Unit</span> <span class="n">ms</span><span class="o">.</span><span class="n">Unit</span> - <span class="n">lastRecord</span> <span class="n">Record</span> -<span class="p">}</span> - -<span class="c">// SetConnection ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">SetDeviceConnection</span><span class="p">(</span><span class="n">client</span> <span class="n">net</span><span class="o">.</span><span class="n">Conn</span><span class="p">)</span> <span class="p">{</span> - <span class="n">proto</span><span class="o">.</span><span class="n">client</span> <span class="o">=</span> <span class="n">client</span> - - <span class="c">// Set timeout to however many seconds ReadTimeout has.</span> - <span class="n">readParams</span> <span class="o">:=</span> <span class="n">DefaultReadParameters</span><span class="p">()</span> - <span class="n">proto</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">SetReadDeadline</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">Now</span><span class="p">()</span><span class="o">.</span><span class="n">Add</span><span class="p">(</span><span class="n">readParams</span><span class="o">.</span><span class="n">Timeout</span><span class="p">))</span> -<span class="p">}</span> - -<span class="c">// SetLogger ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">SetLogger</span><span class="p">(</span><span class="n">logger</span> <span class="n">logger</span><span class="o">.</span><span class="n">Logger</span><span class="p">)</span> <span class="p">{</span> - <span class="n">proto</span><span class="o">.</span><span class="n">Logger</span> <span class="o">=</span> <span class="n">logger</span> -<span class="p">}</span> - -<span class="c">// Read ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">Read</span><span class="p">(</span><span class="n">params</span> <span class="n">ReadParameters</span><span class="p">)</span> <span class="p">(</span><span class="n">Buffer</span><span class="p">,</span> <span class="kt">error</span><span class="p">)</span> <span class="p">{</span> - <span class="n">buf</span> <span class="o">:=</span> <span class="nb">make</span><span class="p">([]</span><span class="kt">byte</span><span class="p">,</span> <span class="n">params</span><span class="o">.</span><span class="n">ByteCount</span><span class="p">)</span> - <span class="k">for</span> <span class="n">i</span> <span class="o">:=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">params</span><span class="o">.</span><span class="n">MaxTimeoutAttempts</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span> <span class="p">{</span> - <span class="k">if</span> <span class="n">bufLen</span><span class="p">,</span> <span class="n">_</span> <span class="o">:=</span> <span class="n">proto</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">Read</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span> <span class="n">bufLen</span> <span class="o">&gt;</span> <span class="m">0</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">Buffer</span><span class="p">{</span><span class="n">buf</span><span class="p">[</span><span class="o">:</span><span class="n">bufLen</span><span class="p">]},</span> <span class="no">nil</span> - <span class="p">}</span> - <span class="n">time</span><span class="o">.</span><span class="n">Sleep</span><span class="p">(</span><span class="n">params</span><span class="o">.</span><span class="n">Timeout</span><span class="p">)</span> - <span class="p">}</span> - <span class="k">return</span> <span class="n">Buffer</span><span class="p">{},</span> <span class="n">errors</span><span class="o">.</span><span class="n">New</span><span class="p">(</span><span class="s">"Device read timeout"</span><span class="p">)</span> -<span class="p">}</span> - -<span class="c">// Write ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">Write</span><span class="p">(</span><span class="n">data</span> <span class="p">[]</span><span class="kt">byte</span><span class="p">)</span> <span class="kt">error</span> <span class="p">{</span> - <span class="k">if</span> <span class="n">bCount</span><span class="p">,</span> <span class="n">err</span> <span class="o">:=</span> <span class="n">proto</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">Write</span><span class="p">(</span><span class="n">data</span><span class="p">);</span> <span class="n">err</span> <span class="o">!=</span> <span class="no">nil</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">err</span> - <span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="n">bCount</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">fmt</span><span class="o">.</span><span class="n">Errorf</span><span class="p">(</span><span class="s">"Failed to write some or all bytes. Expected count: %d, written count: %d"</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">bCount</span><span class="p">)</span> - <span class="p">}</span> - <span class="k">return</span> <span class="no">nil</span> -<span class="p">}</span> - -<span class="c">// SetUnit ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">SetUnit</span><span class="p">(</span><span class="n">unit</span> <span class="n">ms</span><span class="o">.</span><span class="n">Unit</span><span class="p">)</span> <span class="p">{</span> - <span class="n">proto</span><span class="o">.</span><span class="n">Unit</span> <span class="o">=</span> <span class="n">unit</span> -<span class="p">}</span> - -<span class="c">// StoreRecord ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">StoreRecord</span><span class="p">(</span><span class="n">record</span> <span class="o">*</span><span class="n">Record</span><span class="p">)</span> <span class="kt">error</span> <span class="p">{</span> - <span class="k">if</span> <span class="n">record</span> <span class="o">==</span> <span class="no">nil</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">errors</span><span class="o">.</span><span class="n">New</span><span class="p">(</span><span class="s">"Expected a Record. Received nil"</span><span class="p">)</span> - <span class="p">}</span> - - <span class="n">record</span><span class="o">.</span><span class="n">Unit</span> <span class="o">=</span> <span class="n">proto</span><span class="o">.</span><span class="n">Unit</span> - - <span class="n">record</span><span class="o">.</span><span class="n">SetLogger</span><span class="p">(</span><span class="n">proto</span><span class="o">.</span><span class="n">Logger</span><span class="p">)</span> - <span class="k">if</span> <span class="n">err</span> <span class="o">:=</span> <span class="n">record</span><span class="o">.</span><span class="n">Store</span><span class="p">();</span> <span class="n">err</span> <span class="o">!=</span> <span class="no">nil</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">err</span> - <span class="p">}</span> - - <span class="k">if</span> <span class="n">record</span><span class="o">.</span><span class="n">Position</span><span class="o">.</span><span class="n">Timestamp</span><span class="o">.</span><span class="n">After</span><span class="p">(</span><span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Position</span><span class="o">.</span><span class="n">Timestamp</span><span class="p">)</span> <span class="p">{</span> - <span class="c">// Prepare the last possible Record.</span> - <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Flags</span><span class="o">.</span><span class="n">Set</span><span class="p">(</span><span class="n">ms</span><span class="o">.</span><span class="n">Last</span><span class="p">)</span> - <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Unit</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">Unit</span> - <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Position</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">Position</span> - <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Position</span><span class="o">.</span><span class="n">ID</span> <span class="o">=</span> <span class="m">0</span> - <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Position</span><span class="o">.</span><span class="n">Speed</span> <span class="o">=</span> <span class="m">0</span> - <span class="c">// NOTE: Modifying the last Record can be done here.</span> - - <span class="n">proto</span><span class="o">.</span><span class="n">Log</span><span class="p">(</span><span class="n">logger</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="s">"Last known Position timestamp: %v"</span><span class="p">,</span> <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Position</span><span class="o">.</span><span class="n">Timestamp</span><span class="p">)</span> - <span class="p">}</span> - - <span class="k">return</span> <span class="no">nil</span> -<span class="p">}</span> - -<span class="c">// Disconnect ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">DeviceProtocolHeader</span><span class="p">)</span> <span class="n">Disconnect</span><span class="p">()</span> <span class="kt">error</span> <span class="p">{</span> - <span class="n">proto</span><span class="o">.</span><span class="n">client</span><span class="o">.</span><span class="n">Close</span><span class="p">()</span> - <span class="k">if</span> <span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="o">.</span><span class="n">Flags</span><span class="o">.</span><span class="n">Has</span><span class="p">(</span><span class="n">ms</span><span class="o">.</span><span class="n">Last</span><span class="p">)</span> <span class="p">{</span> - <span class="c">// Store last record. Whether this is a valid last trip or not</span> - <span class="c">// is left for upper layers to decide.</span> - <span class="k">if</span> <span class="n">err</span> <span class="o">:=</span> <span class="n">proto</span><span class="o">.</span><span class="n">StoreRecord</span><span class="p">(</span><span class="o">&amp;</span><span class="n">proto</span><span class="o">.</span><span class="n">lastRecord</span><span class="p">);</span> <span class="n">err</span> <span class="o">!=</span> <span class="no">nil</span> <span class="p">{</span> - <span class="n">proto</span><span class="o">.</span><span class="n">Log</span><span class="p">(</span><span class="n">logger</span><span class="o">.</span><span class="n">ERROR</span><span class="p">,</span> <span class="s">"Error: %v"</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span> - <span class="k">return</span> <span class="n">err</span> - <span class="p">}</span> - <span class="p">}</span> - <span class="k">return</span> <span class="no">nil</span> -<span class="p">}</span> - -</code></pre></div></div> - -<p>So, when introducing a new protocol object (say a proprietary ZGPS protocol), we do the following</p> - -<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="k">type</span> <span class="n">ZGPS</span> <span class="k">struct</span> <span class="p">{</span> - <span class="n">DeviceProtocolHeader</span> -<span class="p">}</span> - -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">ZGPS</span><span class="p">)</span> <span class="n">GetIMEI</span><span class="p">()</span> <span class="p">(</span><span class="kt">int64</span><span class="p">,</span> <span class="kt">error</span><span class="p">)</span> <span class="p">{</span> - <span class="c">// TODO: Here goes our proprietary IMEI retrieval implementation</span> -<span class="p">}</span> - -<span class="c">// Acknowledge ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">ZGPS</span><span class="p">)</span> <span class="n">Acknowledge</span><span class="p">()</span> <span class="kt">error</span> <span class="p">{</span> - <span class="c">// TODO: Here goes our proprietery device/request acknowledgment implementation</span> -<span class="p">}</span> - -<span class="c">// Reject ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">ZGPS</span><span class="p">)</span> <span class="n">Reject</span><span class="p">()</span> <span class="kt">error</span> <span class="p">{</span> - <span class="c">// TODO: Here goes our proprietery device/request rejection implementation</span> -<span class="p">}</span> - -<span class="c">// Handle ...</span> -<span class="k">func</span> <span class="p">(</span><span class="n">proto</span> <span class="o">*</span><span class="n">ZGPS</span><span class="p">)</span> <span class="n">Handle</span><span class="p">()</span> <span class="kt">error</span> <span class="p">{</span> - <span class="c">// TODO: Here goes our proprietary data/request processing implementation</span> -<span class="p">}</span> - -</code></pre></div></div> - -<p>What have we objectively achieved here?</p> -<ol> - <li>We’ve set ourselves up for a zero-duplication code base.</li> - <li>We’ve added the ability to introduce higher-level system-wide business logic (take <code class="language-plaintext highlighter-rouge">lastRecord</code> for example) that future SMEs don’t even have to know about, making it easier to specialize at their own space.</li> - <li>Bug hunting is now easier given the code is modularized yet cohesive, and fixes will often be made in one place.</li> -</ol>Fadi Hanna Al-KassOne of the early design challenges we faced when designing the DSP (Device Service Provider) project is coming up with a plug-and-play architecture. DSP’s main responsibility is to read data from a specific tracking device, process and store the data, or send commands and process responses. Different devices come with different protocols, though they share common traits, like they all (all the ones we now support at least) are TCP based. Devices, when connected to DSP, are expected to be recognized so they’re handed to the proper protocol handler. Our silver bullet here is abstraction, but then we’re using Go, and Go doesn’t have native support for abstractions. So how do we solve this?Reverting Changes with Git2018-05-06T05:00:00+00:002018-05-06T05:00:00+00:00/Revering%20Changes%20with%20Git<h1 id="reverting-local-changes">Reverting Local Changes</h1> - -<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code> git checkout <span class="nt">--</span> &lt;file name&gt; -</code></pre></div></div> - -<h1 id="revering-added-changes">Revering Added Changes</h1> - -<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code> git reset <span class="nt">--hard</span> -</code></pre></div></div> - -<h1 id="reverting-changes-from-a-local-commit">Reverting Changes from a Local Commit</h1> - -<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code> git reset <span class="nt">--hard</span> HEAD~1 -</code></pre></div></div> - -<h1 id="reverting-pushed-changes">Reverting Pushed Changes</h1> - -<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code> git reset <span class="nt">--hard</span> HEAD~1 +Jekyll2024-07-31T19:56:33+00:00/feed.xmlIQDevsTechnology Excellence RedefinedZGPS - Achieving Abstraction with Golang2020-05-30T05:00:00+00:002020-05-30T05:00:00+00:00/ZGPS%20-%20Achieving%20Abstraction%20with%20GolangOne of the early design challenges we faced when designing the DSP (Device Service Provider) project is coming up with a plug-and-play architecture. DSP’s main responsibility is to read data from a specific tracking device, process and store the data, or send commands and process responses. Different devices come with different protocols, though they share common traits, like they all (all the ones we now support at least) are TCP based. Devices, when connected to DSP, are expected to be recognized so they’re handed to the proper protocol handler. Our silver bullet here is abstraction, but then we’re using Go, and Go doesn’t have native support for abstractions. So how do we solve this?

+ +

We came up with a list of functions every device –no matter how distinct– must support, and we created an interface called DeviceProtocol that encompasses all these functions. Our interface will include functions like SetDeviceConnection, SetLogger, Read, Write, GetIMEI, SetUnit, Acknowledge, Reject, Handle, StoreRecord, and Disconnect.

+ +

+// DeviceProtocol is a set of functions all supports protocols need to implement.
+type DeviceProtocol interface {
+	// SetDeviceConnection is called to hand the connection over to the device
+	// protocol instance. This is the first thing that happens once a new
+	// device is connected.
+	SetDeviceConnection(net.Conn)
+
+	// SetLogger keeps a copy of a provided Logger for the protocol to consume.
+	SetLogger(logger.Logger)
+
+	// Read allows the protocol to read a specified number of bytes directly
+	// from the device. Refer to the ReadParameters structure to find out
+	// and/or alter the capabilities of the Read function.
+	Read(ReadParameters) (Buffer, error)
+
+	// Write allows the protocol to send byte streams directly to the device.
+	// If the number of bytes written does NOT comport with the number of bytes
+	// in the slice passed to the function, an error is returned.
+	Write([]byte) error
+
+	// GetIMEI does what is necessary for the protocol to retrieve the IMEI from
+	// the device. Failures can be expected, and tend to be more occasional, then
+	// they need to be, so the caller needs to always watch out for errors. That
+	// is, if `error` is anything other than nil, the proper action is to reject
+	// the connection and bailout.
+	GetIMEI() (int64, error)
+
+	// Acknowledge is automatically called once an IMEI is retrieved and
+	// authenticated.
+	// NOTE: Units that are marked off as disabled in the database won't
+	// be acknowledged.
+	Acknowledge() error
+
+	// Reject is automatically called if the device fails to send an IMEI
+	// within a specified period of time, or if the IMEI is not found in
+	// the database or if the database object is marked off as disabled.
+	// This function is automatically called right before Disconnect is.
+	Reject() error
+
+	// SetUnit is called once a device is acknowledged. The point of this
+	// call is to hand over the Unit object to the protocol so that the
+	// protocol is capable of inferring the Unit identifier.
+	SetUnit(ms.Unit)
+
+	// Handle is the entry point to a device handler. Every supported protocol
+	// needs to implement this function. <b>No abstraction version of this
+	// function is provided</b> for the sole reason that different devices
+	// come with different protocols.
+	Handle() error
+
+	// StoreRecord is responsible for processing one device Record at a time.
+	// Record (defined in Record.go) is supposed to at least have a Unit
+	// object (defined in ms/Unit.go) and a Position object (defined in
+	// ms/Position.go). Whether the Position is valid or not is decided by
+	// its own microservice later.
+	StoreRecord(*Record) error
+
+	// Disconnect is the last function called towards the end of the lifecycle
+	// of a protocol instance. That is, the function is called before the
+	// protocol instance is dismissed forever. Protocol lifecycle comes to an
+	// end when the device has been idle (no data received from a device within a
+	// designated timeframe), or if the device fails to send an IMEI or if the
+	// device IMEI is not associated with any Unit objects in the database, or
+	// if the Unit object is marked as disabled.
+	Disconnect() error
+}
+
+ +

Soon after a tracking device connects, we call SetDeviceConnection with our connection object, we then call GetIMEI that’ll internally compose a device identifier request and send it to the device using the Write function. The response is then retrieved with the Read function. Our GetIMEI function returns either the device unique identifier or an error (happens when the client fails to provide its IMEI within a designated timeframe, or when invalid data is provided or when the function identifies a suspicious activity).

+ +

A lot of these functions will have identical internal implementations. For instance,

+
    +
  • SetDeviceConnection, SetLogger and SetUnit are a common one-liner across all protocol implementations.
  • +
  • Read and Write will be identical across all protocols given Read is flexible with its ReadParameters and Write blindlessly transmits a given slice of bites. No device-specific intelligence required.
  • +
  • StoreRecord is a device-agnostic microservice-consuming function that doesn’t need to be reimplemented for every protocol.
  • +
  • Disconnect performs some Record-related actions (device-agnostic, remember?) and closes the TCP connection generically.
  • +
+ +

The way around the issue is to have a form of abstraction that allows protocols to adopt at will and override when needed. Problem is Go isn’t an OOP language (that’s not to say OOP can’t be employed in the language), and so class abstraction isn’t a first-class construct of the language. What we do here is we create a DeviceProtocolHeader with our common functions defined and implemented, and aggregate the object in every protocol object we create:

+ +

+// DeviceProtocolHeader has a set of abstract functions that device protocols tend to have
+// in common. Instead of having to re-implement the same errorprocedures for every
+// Protocol implementation, it is recommended to include this header and have
+// the extra functionality at no cost.
+type DeviceProtocolHeader struct {
+	logger.Logger
+	client     net.Conn
+	Unit       ms.Unit
+	lastRecord Record
+}
+
+// SetConnection ...
+func (proto *DeviceProtocolHeader) SetDeviceConnection(client net.Conn) {
+	proto.client = client
+
+	// Set timeout to however many seconds ReadTimeout has.
+	readParams := DefaultReadParameters()
+	proto.client.SetReadDeadline(time.Now().Add(readParams.Timeout))
+}
+
+// SetLogger ...
+func (proto *DeviceProtocolHeader) SetLogger(logger logger.Logger) {
+	proto.Logger = logger
+}
+
+// Read ...
+func (proto *DeviceProtocolHeader) Read(params ReadParameters) (Buffer, error) {
+	buf := make([]byte, params.ByteCount)
+	for i := 0; i <= params.MaxTimeoutAttempts; i++ {
+		if bufLen, _ := proto.client.Read(buf); bufLen > 0 {
+			return Buffer{buf[:bufLen]}, nil
+		}
+		time.Sleep(params.Timeout)
+	}
+	return Buffer{}, errors.New("Device read timeout")
+}
+
+// Write ...
+func (proto *DeviceProtocolHeader) Write(data []byte) error {
+	if bCount, err := proto.client.Write(data); err != nil {
+		return err
+	} else if bCount != len(data) {
+		return fmt.Errorf("Failed to write some or all bytes. Expected count: %d, written count: %d", len(data), bCount)
+	}
+	return nil
+}
+
+// SetUnit ...
+func (proto *DeviceProtocolHeader) SetUnit(unit ms.Unit) {
+	proto.Unit = unit
+}
+
+// StoreRecord ...
+func (proto *DeviceProtocolHeader) StoreRecord(record *Record) error {
+	if record == nil {
+		return errors.New("Expected a Record. Received nil")
+	}
+
+	record.Unit = proto.Unit
+
+	record.SetLogger(proto.Logger)
+	if err := record.Store(); err != nil {
+		return err
+	}
+
+	if record.Position.Timestamp.After(proto.lastRecord.Position.Timestamp) {
+		// Prepare the last possible Record.
+		proto.lastRecord.Flags.Set(ms.Last)
+		proto.lastRecord.Unit = record.Unit
+		proto.lastRecord.Position = record.Position
+		proto.lastRecord.Position.ID = 0
+		proto.lastRecord.Position.Speed = 0
+		// NOTE: Modifying the last Record can be done here.
+
+		proto.Log(logger.INFO, "Last known Position timestamp: %v", proto.lastRecord.Position.Timestamp)
+	}
+
+	return nil
+}
+
+// Disconnect ...
+func (proto *DeviceProtocolHeader) Disconnect() error {
+	proto.client.Close()
+	if proto.lastRecord.Flags.Has(ms.Last) {
+		// Store last record. Whether this is a valid last trip or not
+		// is left for upper layers to decide.
+		if err := proto.StoreRecord(&proto.lastRecord); err != nil {
+			proto.Log(logger.ERROR, "Error: %v", err)
+			return err
+		}
+	}
+	return nil
+}
+
+
+ +

So, when introducing a new protocol object (say a proprietary ZGPS protocol), we do the following

+ +

+type ZGPS struct {
+    DeviceProtocolHeader
+}
+
+func (proto *ZGPS) GetIMEI() (int64, error) {
+    // TODO: Here goes our proprietary IMEI retrieval implementation
+}
+
+// Acknowledge ...
+func (proto *ZGPS) Acknowledge() error {
+    // TODO: Here goes our proprietery device/request acknowledgment implementation
+}
+
+// Reject ...
+func (proto *ZGPS) Reject() error {
+	// TODO: Here goes our proprietery device/request rejection implementation
+}
+
+// Handle ...
+func (proto *ZGPS) Handle() error {
+    // TODO: Here goes our proprietary data/request processing implementation
+}
+
+
+ +

What have we objectively achieved here?

+
    +
  1. We’ve set ourselves up for a zero-duplication code base.
  2. +
  3. We’ve added the ability to introduce higher-level system-wide business logic (take lastRecord for example) that future SMEs don’t even have to know about, making it easier to specialize at their own space.
  4. +
  5. Bug hunting is now easier given the code is modularized yet cohesive, and fixes will often be made in one place.
  6. +
]]>
Fadi Hanna Al-Kass
Reverting Changes with Git2018-05-06T05:00:00+00:002018-05-06T05:00:00+00:00/Revering%20Changes%20with%20GitReverting Local Changes

+ +
  git checkout -- <file name>
+
+ +

Revering Added Changes

+ +
  git reset --hard
+
+ +

Reverting Changes from a Local Commit

+ +
  git reset --hard HEAD~1
+
+ +

Reverting Pushed Changes

+ +
  git reset --hard HEAD~1
   git push origin +master
-</code></pre></div></div>Fadi Hanna Al-KassReverting Local ChangesGeneric Types in Strongly Typed Languages2017-11-14T05:00:00+00:002017-11-14T05:00:00+00:00/Generic%20Types%20in%20Strongly%20Typed%20Languages<p>Few days ago, I wrote <a href="https://github.com/alexcorvi/mongots">mongots</a>, an alternative API for <a href="https://www.mongodb.com/">MongoDB</a> to make it work better with <a href="https://www.typescriptlang.org/">TypeScript</a> (a strongly-typed language that compiles to JS) on the NodeJS environment.</p>
+
]]>Fadi Hanna Al-KassGeneric Types in Strongly Typed Languages2017-11-14T05:00:00+00:002017-11-14T05:00:00+00:00/Generic%20Types%20in%20Strongly%20Typed%20LanguagesFew days ago, I wrote mongots, an alternative API for MongoDB to make it work better with TypeScript (a strongly-typed language that compiles to JS) on the NodeJS environment.

-<p>“Alternative” is an overstatement, since it is totally built on top of the native MongoDB driver, and it’s not an ODM like <a href="http://mongoosejs.com/">Mongoose</a>, and it doesn’t provide any new functionality.</p> +

“Alternative” is an overstatement, since it is totally built on top of the native MongoDB driver, and it’s not an ODM like Mongoose, and it doesn’t provide any new functionality.

-<p>Then why did I write it? The answer is: “stronger types”. The native MongoDB driver has <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mongodb">its type definitions in the DefinitelyTyped repository</a>, can be easily installed, but I was annoyed by all the <code class="language-plaintext highlighter-rouge">any</code> keywords it was littered with. It’s not that the authors don’t know how to make it more strongly typed, it’s just that MongoDB native driver API has been designed in a way (for JavaScript) that makes strong typing almost impossible with some cases.</p> +

Then why did I write it? The answer is: “stronger types”. The native MongoDB driver has its type definitions in the DefinitelyTyped repository, can be easily installed, but I was annoyed by all the any keywords it was littered with. It’s not that the authors don’t know how to make it more strongly typed, it’s just that MongoDB native driver API has been designed in a way (for JavaScript) that makes strong typing almost impossible with some cases.

-<p>My journey in creating this library has given me an insight on how generic types can be so helpful in some cases, and after seeing some tweets criticizing TypeScript’s generic types, I’ve decided to write this post.</p> +

My journey in creating this library has given me an insight on how generic types can be so helpful in some cases, and after seeing some tweets criticizing TypeScript’s generic types, I’ve decided to write this post.

-<p>Throughout this post, I’ll use TypeScript as an example, because everyone with a JavaScript background can comprehend the code, and personally, it’s my language of choice.</p> +

Throughout this post, I’ll use TypeScript as an example, because everyone with a JavaScript background can comprehend the code, and personally, it’s my language of choice.

-<h2 id="introduction-to-generic-types">Introduction to Generic Types</h2> +

Introduction to Generic Types

-<p>Let’s start with an example, a common pattern for JavaScript developers is to copy JSON objects using <code class="language-plaintext highlighter-rouge">JSON.stringify</code> and <code class="language-plaintext highlighter-rouge">JSON.parse</code>, like this:</p> +

Let’s start with an example, a common pattern for JavaScript developers is to copy JSON objects using JSON.stringify and JSON.parse, like this:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyObject</span> <span class="p">(</span><span class="nx">obj</span><span class="p">)</span> <span class="p">{</span> - <span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span> - <span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span> - <span class="k">return</span> <span class="nx">theCopy</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
function copyObject (obj) {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
+    return theCopy;
+}
+
-<p>The parameter <code class="language-plaintext highlighter-rouge">obj</code> in the above example can be anything, it can be a number, a string, an array, object literal …etc. So adding type definitions might be quite useless (without generic types):</p> +

The parameter obj in the above example can be anything, it can be a number, a string, an array, object literal …etc. So adding type definitions might be quite useless (without generic types):

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyObject</span> <span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">any</span><span class="p">):</span> <span class="nx">any</span> <span class="p">{</span> - <span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span> - <span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span> - <span class="k">return</span> <span class="nx">theCopy</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
function copyObject (obj: any): any {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
+    return theCopy;
+}
+
-<p>But with generic types, our function becomes as strongly typed as any function can be:</p> +

But with generic types, our function becomes as strongly typed as any function can be:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyObject</span><span class="o">&lt;</span><span class="nx">T</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">T</span><span class="p">):</span> <span class="nx">T</span> <span class="p">{</span> - <span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span> - <span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span> - <span class="k">return</span> <span class="nx">theCopy</span><span class="p">;</span> -<span class="p">}</span> +
function copyObject<T>(obj: T): T {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
+    return theCopy;
+}
 
-<span class="kd">const</span> <span class="nx">myObject</span> <span class="o">=</span> <span class="p">{</span> <span class="na">a</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="na">b</span><span class="p">:</span> <span class="mi">3</span> <span class="p">};</span>
+const myObject = { a: 0, b: 3 };
 
-<span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">copyObject</span><span class="p">(</span><span class="nx">myObject</span><span class="p">);</span>
+const theCopy = copyObject(myObject);
 
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">theCopy</span><span class="p">.</span><span class="nx">a</span><span class="p">);</span> <span class="c1">// OK!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">theCopy</span><span class="p">.</span><span class="nx">b</span><span class="p">);</span> <span class="c1">// OK!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">theCopy</span><span class="p">.</span><span class="nx">c</span><span class="p">);</span> <span class="c1">// Compile Error!</span>
-</code></pre></div></div>
+console.log(theCopy.a); // OK!
+console.log(theCopy.b); // OK!
+console.log(theCopy.c); // Compile Error!
+
-<p>The syntax for writing generic types is like many languages, before the parameters using the angle brackets.</p> +

The syntax for writing generic types is like many languages, before the parameters using the angle brackets.

-<p>Another example of how you can make use of generic types is when requesting data from a server.</p> +

Another example of how you can make use of generic types is when requesting data from a server.

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">getFromServer</span><span class="o">&lt;</span><span class="nx">DataSchema</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">url</span><span class="p">:</span> <span class="nx">string</span><span class="p">):</span> <span class="nx">Data</span> <span class="p">{</span> - <span class="c1">// make the request</span> - <span class="c1">// and return the data</span> -<span class="p">}</span> +
function getFromServer<DataSchema>(url: string): Data {
+    // make the request
+    // and return the data
+}
 
-<span class="kr">interface</span> <span class="nx">Employees</span> <span class="p">{</span>
-    <span class="nl">departmentA</span><span class="p">:</span> <span class="nx">string</span><span class="p">[];</span>
-    <span class="nl">departmentB</span><span class="p">:</span> <span class="nx">string</span><span class="p">[];</span>
-<span class="p">};</span>
+interface Employees {
+    departmentA: string[];
+    departmentB: string[];
+};
 
-<span class="kd">const</span> <span class="nx">employees</span> <span class="o">=</span> <span class="nx">getFromServer</span><span class="o">&lt;</span><span class="nx">Employees</span><span class="o">&gt;</span><span class="p">(</span><span class="dl">"</span><span class="s2">http://www.example.com/api/employees.json</span><span class="dl">"</span><span class="p">);</span>
+const employees = getFromServer<Employees>("http://www.example.com/api/employees.json");
 
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">employees</span><span class="p">.</span><span class="nx">departmentA</span><span class="p">);</span> <span class="c1">// OK!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">employees</span><span class="p">.</span><span class="nx">departmentB</span><span class="p">);</span> <span class="c1">// OK!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">employees</span><span class="p">.</span><span class="nx">departmentC</span><span class="p">);</span> <span class="c1">// Compile error!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">employees</span><span class="p">.</span><span class="nx">departmentA</span><span class="p">.</span><span class="nx">length</span><span class="p">)</span> <span class="c1">// OK!</span>
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">employees</span><span class="p">.</span><span class="nx">departmentA</span> <span class="o">+</span> <span class="nx">employees</span><span class="p">.</span><span class="nx">departmentB</span><span class="p">);</span>
-<span class="c1">// ^ Compile errors because they are arrays</span>
-</code></pre></div></div>
+console.log(employees.departmentA); // OK!
+console.log(employees.departmentB); // OK!
+console.log(employees.departmentC); // Compile error!
+console.log(employees.departmentA.length) // OK!
+console.log(employees.departmentA + employees.departmentB);
+// ^ Compile errors because they are arrays
+
-<p>The previous example shows how generic types are treated like additional arguments in the function. And that’s what they really are, <em>additional arguments</em>. In the first example, however, TypeScript was smart enough to determine the type of the passed value, and we did not need to pass any generic type values in angle brackets. Typescript can also be smart and notify you when you do something like this:</p> +

The previous example shows how generic types are treated like additional arguments in the function. And that’s what they really are, additional arguments. In the first example, however, TypeScript was smart enough to determine the type of the passed value, and we did not need to pass any generic type values in angle brackets. Typescript can also be smart and notify you when you do something like this:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyObject</span><span class="o">&lt;</span><span class="nx">T</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">T</span><span class="p">):</span> <span class="nx">T</span> <span class="p">{</span> - <span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span> - <span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span> - <span class="k">return</span> <span class="nx">theCopy</span><span class="p">;</span> -<span class="p">}</span> +
function copyObject<T>(obj: T): T {
+    const string = JSON.stringify(obj);
+    const theCopy = JSON.parse(string);
+    return theCopy;
+}
 
-<span class="kd">const</span> <span class="nx">myObject</span> <span class="o">=</span> <span class="p">{</span> <span class="na">a</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="na">b</span><span class="p">:</span> <span class="mi">3</span> <span class="p">};</span>
+const myObject = { a: 0, b: 3 };
 
-<span class="kd">const</span> <span class="nx">theCopy</span> <span class="o">=</span> <span class="nx">copyObject</span><span class="o">&lt;</span><span class="nx">number</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">myObject</span><span class="p">);</span>
-<span class="c1">// ^ Compile Error:</span>
-<span class="c1">// Argument of type '{ a: number; b: number; }'</span>
-<span class="c1">// is not assignable to parameter of type 'number'.</span>
-</code></pre></div></div>
+const theCopy = copyObject<number>(myObject);
+// ^ Compile Error:
+// Argument of type '{ a: number; b: number; }'
+// is not assignable to parameter of type 'number'.
+
-<p>Now if you’re writing your server and your front end with typescript you don’t have to write the interface <code class="language-plaintext highlighter-rouge">Employees</code> twice, what you can do is structure your project in a way that the server (back-end) and the front-end share a directory where you keep type definitions.</p> +

Now if you’re writing your server and your front end with typescript you don’t have to write the interface Employees twice, what you can do is structure your project in a way that the server (back-end) and the front-end share a directory where you keep type definitions.

-<p>So, in the types directory, you can have this file <code class="language-plaintext highlighter-rouge">interface.employee.ts</code></p> +

So, in the types directory, you can have this file interface.employee.ts

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kr">interface</span> <span class="nx">Employee</span> <span class="p">{</span> - <span class="nl">name</span><span class="p">:</span> <span class="nx">string</span><span class="p">;</span> - <span class="nl">birth</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
export interface Employee {
+    name: string;
+    birth: number;
+}
+
-<p>In your server:</p> +

In your server:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="p">{</span> <span class="nx">Employee</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">../types/interface.employee.ts</span><span class="dl">"</span> -<span class="kd">const</span> <span class="nx">employeesCollection</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">myDB</span><span class="p">.</span><span class="nx">collection</span><span class="o">&lt;</span><span class="nx">Employee</span><span class="o">&gt;</span><span class="p">(</span><span class="dl">"</span><span class="s2">employees</span><span class="dl">"</span><span class="p">);</span> -</code></pre></div></div> +
import { Employee } from "../types/interface.employee.ts"
+const employeesCollection = new myDB.collection<Employee>("employees");
+
-<p>And in your front end:</p> +

And in your front end:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="p">{</span> <span class="nx">Employee</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">../types/interface.employee.ts</span><span class="dl">"</span> -<span class="kd">const</span> <span class="nx">employees</span> <span class="o">=</span> <span class="nx">getFromServer</span><span class="o">&lt;</span><span class="nx">Employee</span><span class="o">&gt;</span><span class="p">(</span><span class="dl">"</span><span class="s2">http://www.example.com/api/employees/ahmed.json</span><span class="dl">"</span><span class="p">);</span> -</code></pre></div></div> +
import { Employee } from "../types/interface.employee.ts"
+const employees = getFromServer<Employee>("http://www.example.com/api/employees/ahmed.json");
+
-<p>And that barely scratches the surface of how powerful generic types can be.</p> +

And that barely scratches the surface of how powerful generic types can be.

-<h2 id="restricting-generic-types">Restricting Generic Types</h2> +

Restricting Generic Types

-<p>You can also restrict how generic your generic types can be, for example, let’s say that we have a function that logs the length of the passed value (whatever it is):</p> +

You can also restrict how generic your generic types can be, for example, let’s say that we have a function that logs the length of the passed value (whatever it is):

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">logLength</span> <span class="p">(</span><span class="nx">val</span><span class="p">)</span> <span class="p">{</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">val</span><span class="p">.</span><span class="nx">length</span><span class="p">);</span> -<span class="p">}</span> -</code></pre></div></div> +
function logLength (val) {
+    console.log(val.length);
+}
+
-<p>But there are only two built-in types in javascript that have the length property, <code class="language-plaintext highlighter-rouge">String</code> and <code class="language-plaintext highlighter-rouge">Array</code>. So what we can do is set a constraint on the generic type like this:</p> +

But there are only two built-in types in javascript that have the length property, String and Array. So what we can do is set a constraint on the generic type like this:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">interface</span> <span class="nx">hasLength</span> <span class="p">{</span> - <span class="nl">length</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> -<span class="p">}</span> +
interface hasLength {
+    length: number;
+}
 
-<span class="kd">function</span> <span class="nx">logLength</span> <span class="o">&lt;</span><span class="nx">T</span> <span class="kd">extends</span> <span class="nx">hasLength</span><span class="o">&gt;</span> <span class="p">(</span><span class="nx">val</span><span class="p">:</span> <span class="nx">T</span><span class="p">)</span> <span class="p">{</span>
-    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">val</span><span class="p">.</span><span class="nx">length</span><span class="p">);</span>
-<span class="p">}</span>
+function logLength <T extends hasLength> (val: T) {
+    console.log(val.length);
+}
 
-<span class="nx">logLength</span><span class="p">(</span><span class="dl">"</span><span class="s2">string</span><span class="dl">"</span><span class="p">);</span> <span class="c1">// OK</span>
-<span class="nx">logLength</span><span class="p">([</span><span class="dl">"</span><span class="s2">a</span><span class="dl">"</span><span class="p">,</span><span class="dl">"</span><span class="s2">b</span><span class="dl">"</span><span class="p">,</span><span class="dl">"</span><span class="s2">c</span><span class="dl">"</span><span class="p">]);</span> <span class="c1">// OK</span>
-<span class="nx">logLength</span><span class="p">({</span>
-    <span class="na">width</span><span class="p">:</span> <span class="mi">300</span><span class="p">,</span>
-    <span class="na">length</span><span class="p">:</span> <span class="mi">600</span>
-<span class="p">});</span> <span class="c1">// Also OK because it has the length property</span>
-<span class="nx">logLength</span><span class="p">(</span><span class="mi">17</span><span class="p">);</span> <span class="c1">// Compile Error!</span>
-</code></pre></div></div>
+logLength("string"); // OK
+logLength(["a","b","c"]); // OK
+logLength({
+    width: 300,
+    length: 600
+}); // Also OK because it has the length property
+logLength(17); // Compile Error!
+
-<h2 id="index-types-with-generic-types">Index Types With Generic Types</h2> +

Index Types With Generic Types

-<p>A more elaborate example is a function that copies (Using <code class="language-plaintext highlighter-rouge">JSON.stringify</code> and <code class="language-plaintext highlighter-rouge">JSON.parse</code>) a property of any object that it receives.</p> +

A more elaborate example is a function that copies (Using JSON.stringify and JSON.parse) a property of any object that it receives.

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyProperty</span><span class="o">&lt;</span><span class="nx">OBJ</span><span class="p">,</span> <span class="nx">KEY</span> <span class="kd">extends</span> <span class="nx">keyof</span> <span class="nx">OBJ</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">OBJ</span><span class="p">,</span> <span class="nx">key</span><span class="p">:</span> <span class="nx">KEY</span><span class="p">):</span> <span class="nx">OBJ</span><span class="p">[</span><span class="nx">KEY</span><span class="p">]</span> <span class="p">{</span> - <span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">[</span><span class="nx">key</span><span class="p">]);</span> - <span class="kd">const</span> <span class="nx">copied</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span> - <span class="k">return</span> <span class="nx">copied</span><span class="p">;</span> -<span class="p">}</span> +
function copyProperty<OBJ, KEY extends keyof OBJ>(obj: OBJ, key: KEY): OBJ[KEY] {
+    const string = JSON.stringify(obj[key]);
+    const copied = JSON.parse(string);
+    return copied;
+}
 
-<span class="kd">const</span> <span class="nx">car</span> <span class="o">=</span> <span class="p">{</span> <span class="na">engine</span><span class="p">:</span> <span class="dl">"</span><span class="s2">v8</span><span class="dl">"</span><span class="p">,</span> <span class="na">milage</span><span class="p">:</span> <span class="mi">123000</span><span class="p">,</span> <span class="na">color</span><span class="p">:</span> <span class="dl">"</span><span class="s2">red</span><span class="dl">"</span> <span class="p">};</span>
-<span class="kd">const</span> <span class="nx">animal</span> <span class="o">=</span> <span class="p">{</span> <span class="na">name</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Domestic Cat</span><span class="dl">"</span><span class="p">,</span> <span class="na">species</span><span class="p">:</span> <span class="dl">"</span><span class="s2">silvestris</span><span class="dl">"</span> <span class="p">};</span>
+const car = { engine: "v8", milage: 123000, color: "red" };
+const animal = { name: "Domestic Cat", species: "silvestris" };
 
-<span class="nx">copyProperty</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span> <span class="dl">"</span><span class="s2">engine</span><span class="dl">"</span><span class="p">);</span> <span class="c1">// OK</span>
-<span class="nx">copyProperty</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span> <span class="dl">"</span><span class="s2">color</span><span class="dl">"</span><span class="p">).</span><span class="nx">length</span><span class="p">;</span> <span class="c1">// OK</span>
-<span class="nx">copyProperty</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span> <span class="dl">"</span><span class="s2">milage</span><span class="dl">"</span><span class="p">).</span><span class="nx">length</span><span class="p">;</span> <span class="c1">// Compile error, because it's a number!</span>
-<span class="nx">copyProperty</span><span class="p">(</span><span class="nx">animal</span><span class="p">,</span> <span class="dl">"</span><span class="s2">color</span><span class="dl">"</span><span class="p">);</span> <span class="c1">// Compile error, because "color" is not a property on that object!</span>
-<span class="c1">// so you can only pass the object's property names and</span>
-<span class="c1">// typescript will be smart enough to determine their values</span>
-</code></pre></div></div>
+copyProperty(car, "engine"); // OK
+copyProperty(car, "color").length; // OK
+copyProperty(car, "milage").length; // Compile error, because it's a number!
+copyProperty(animal, "color"); // Compile error, because "color" is not a property on that object!
+// so you can only pass the object's property names and
+// typescript will be smart enough to determine their values
+
-<p>Now let’s step it up a bit, by making our <code class="language-plaintext highlighter-rouge">copyProperty</code> able to copy multiple properties on the same call, so the second argument, will be an array of property names that will be copied and returned as an array.</p> +

Now let’s step it up a bit, by making our copyProperty able to copy multiple properties on the same call, so the second argument, will be an array of property names that will be copied and returned as an array.

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">copyProperties</span><span class="o">&lt;</span><span class="nx">OBJ</span><span class="p">,</span> <span class="nx">KEY</span> <span class="kd">extends</span> <span class="nx">keyof</span> <span class="nx">OBJ</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">OBJ</span><span class="p">,</span> <span class="nx">keys</span><span class="p">:</span> <span class="nb">Array</span><span class="o">&lt;</span><span class="nx">KEY</span><span class="o">&gt;</span><span class="p">):</span> <span class="nb">Array</span><span class="o">&lt;</span><span class="nx">OBJ</span><span class="p">[</span><span class="nx">KEY</span><span class="p">]</span><span class="o">&gt;</span> <span class="p">{</span> - <span class="k">return</span> <span class="nx">keys</span> - <span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">x</span> <span class="o">=&gt;</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">[</span><span class="nx">x</span><span class="p">]))</span> - <span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="nx">x</span> <span class="o">=&gt;</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span> -<span class="p">}</span> +
function copyProperties<OBJ, KEY extends keyof OBJ>(obj: OBJ, keys: Array<KEY>): Array<OBJ[KEY]> {
+	return keys
+		.map(x => JSON.stringify(obj[x]))
+		.map(x => JSON.parse(x))
+}
 
-<span class="kd">const</span> <span class="nx">car</span> <span class="o">=</span> <span class="p">{</span> <span class="na">engine</span><span class="p">:</span> <span class="dl">"</span><span class="s2">v8</span><span class="dl">"</span><span class="p">,</span> <span class="na">milage</span><span class="p">:</span> <span class="mi">123000</span><span class="p">,</span> <span class="na">color</span><span class="p">:</span> <span class="dl">"</span><span class="s2">red</span><span class="dl">"</span> <span class="p">};</span>
+const car = { engine: "v8", milage: 123000, color: "red" };
 
-<span class="kd">const</span> <span class="nx">a</span><span class="p">:</span> <span class="nx">string</span><span class="p">[]</span> <span class="o">=</span> <span class="nx">copyProperties</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span> <span class="p">[</span><span class="dl">"</span><span class="s2">engine</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">color</span><span class="dl">"</span><span class="p">]);</span> <span class="c1">// OK</span>
-<span class="kd">const</span> <span class="nx">b</span><span class="p">:</span> <span class="nx">string</span><span class="p">[]</span> <span class="o">=</span> <span class="nx">copyProperties</span><span class="p">(</span><span class="nx">car</span><span class="p">,</span> <span class="p">[</span><span class="dl">"</span><span class="s2">engine</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">milage</span><span class="dl">"</span><span class="p">]);</span>
-<span class="c1">// ^ Compile Error! because one of the array values is a number</span>
-<span class="c1">// and that's because one of the properties</span>
-<span class="c1">// we're copying is "milage".</span>
-</code></pre></div></div>
+const a: string[] = copyProperties(car, ["engine", "color"]); // OK
+const b: string[] = copyProperties(car, ["engine", "milage"]);
+// ^ Compile Error! because one of the array values is a number
+// and that's because one of the properties
+// we're copying is "milage".
+
-<h2 id="mapped-generic-types">Mapped Generic Types</h2> +

Mapped Generic Types

-<p>Sometimes, we’d like to modify the values of the object while copying it. For example, we have this document object:</p> +

Sometimes, we’d like to modify the values of the object while copying it. For example, we have this document object:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nb">document</span> <span class="o">=</span> <span class="p">{</span> - <span class="na">title</span><span class="p">:</span> <span class="dl">"</span><span class="s2">New Document</span><span class="dl">"</span><span class="p">,</span> - <span class="na">content</span><span class="p">:</span> <span class="dl">"</span><span class="s2">document content ...</span><span class="dl">"</span><span class="p">,</span> - <span class="na">createdAt</span><span class="p">:</span> <span class="mi">1510680155148</span> -<span class="p">};</span> -</code></pre></div></div> +
const document = {
+    title: "New Document",
+    content: "document content ...",
+    createdAt: 1510680155148
+};
+
-<p>We’d like the copy to hold a different value for the <code class="language-plaintext highlighter-rouge">createdAt</code> property. So we’ll write a function that copies objects and takes a second argument that will be property names and values to be edited.</p> +

We’d like the copy to hold a different value for the createdAt property. So we’ll write a function that copies objects and takes a second argument that will be property names and values to be edited.

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="c1">// this is a generic type, it takes any type (object)</span> -<span class="c1">// as an argument and returns the same type</span> -<span class="c1">// but with every property being optional</span> -<span class="nx">type</span> <span class="nx">Partial</span><span class="o">&lt;</span><span class="nx">T</span><span class="o">&gt;</span> <span class="o">=</span> <span class="p">{</span> - <span class="p">[</span><span class="nx">P</span> <span class="k">in</span> <span class="nx">keyof</span> <span class="nx">T</span><span class="p">]?:</span> <span class="nx">T</span><span class="p">[</span><span class="nx">P</span><span class="p">]</span> -<span class="p">}</span> +

+// this is a generic type, it takes any type (object)
+// as an argument and returns the same type
+// but with every property being optional
+type Partial<T> = {
+	[P in keyof T]?: T[P]
+}
 
-<span class="kd">function</span> <span class="nx">copyAndModify</span><span class="o">&lt;</span><span class="nx">T</span><span class="o">&gt;</span><span class="p">(</span><span class="nx">obj</span><span class="p">:</span> <span class="nx">T</span><span class="p">,</span> <span class="nx">mods</span><span class="p">:</span><span class="nx">Partial</span><span class="o">&lt;</span><span class="nx">T</span><span class="o">&gt;</span><span class="p">):</span> <span class="nx">T</span> <span class="p">{</span>
-	<span class="kd">const</span> <span class="nx">string</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span>
-	<span class="kd">const</span> <span class="nx">copy</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">string</span><span class="p">);</span>
-	<span class="nb">Object</span><span class="p">.</span><span class="nx">keys</span><span class="p">(</span><span class="nx">mods</span><span class="p">).</span><span class="nx">forEach</span><span class="p">(</span><span class="nx">key</span> <span class="o">=&gt;</span> <span class="p">{</span>
-		<span class="nx">copy</span><span class="p">[</span><span class="nx">key</span><span class="p">]</span> <span class="o">=</span> <span class="nx">mods</span><span class="p">[</span><span class="nx">key</span><span class="p">];</span>
-	<span class="p">});</span>
-	<span class="k">return</span> <span class="nx">copy</span><span class="p">;</span>
-<span class="p">}</span>
+function copyAndModify<T>(obj: T, mods:Partial<T>): T {
+	const string = JSON.stringify(obj);
+	const copy = JSON.parse(string);
+	Object.keys(mods).forEach(key => {
+		copy[key] = mods[key];
+	});
+	return copy;
+}
 
 
-<span class="kd">const</span> <span class="nx">doc</span> <span class="o">=</span> <span class="p">{</span>
-    <span class="na">title</span><span class="p">:</span> <span class="dl">"</span><span class="s2">New Document</span><span class="dl">"</span><span class="p">,</span>
-    <span class="na">content</span><span class="p">:</span> <span class="dl">"</span><span class="s2">document content ...</span><span class="dl">"</span><span class="p">,</span>
-    <span class="na">createdAt</span><span class="p">:</span> <span class="mi">1510680155148</span>
-<span class="p">};</span>
+const doc = {
+    title: "New Document",
+    content: "document content ...",
+    createdAt: 1510680155148
+};
 
 
-<span class="nx">copyAndModify</span><span class="p">(</span><span class="nx">doc</span><span class="p">,</span> <span class="p">{</span> <span class="na">createdAt</span><span class="p">:</span> <span class="k">new</span> <span class="nb">Date</span><span class="p">().</span><span class="nx">getTime</span><span class="p">()</span> <span class="p">})</span> <span class="c1">// OK</span>
-<span class="nx">copyAndModify</span><span class="p">(</span><span class="nx">doc</span><span class="p">,</span> <span class="p">{</span> <span class="na">title</span><span class="p">:</span> <span class="dl">"</span><span class="s2">New title</span><span class="dl">"</span> <span class="p">})</span> <span class="c1">// OK</span>
-<span class="nx">copyAndModify</span><span class="p">(</span><span class="nx">doc</span><span class="p">,</span> <span class="p">{</span> <span class="na">content</span><span class="p">:</span> <span class="mi">0</span> <span class="p">})</span>
-<span class="c1">// Compile Error!</span>
-<span class="c1">// Because content is a string, so we must</span>
-<span class="c1">// put a string when modifying it</span>
+copyAndModify(doc, { createdAt: new Date().getTime() }) // OK
+copyAndModify(doc, { title: "New title" }) // OK
+copyAndModify(doc, { content: 0 })
+// Compile Error!
+// Because content is a string, so we must
+// put a string when modifying it
 
 
-<span class="nx">copyAndModify</span><span class="p">(</span><span class="nx">doc</span><span class="p">,</span> <span class="p">{</span> <span class="na">author</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Some one</span><span class="dl">"</span> <span class="p">})</span>
-<span class="c1">// Compile Error!</span>
-<span class="c1">// Because we did not have the property author on the original document</span>
+copyAndModify(doc, { author: "Some one" })
+// Compile Error!
+// Because we did not have the property author on the original document
 
-</code></pre></div></div>
+
-<p>So those were some of the ways that you can utilize generic types to write a more safe and expressive code.</p> +

So those were some of the ways that you can utilize generic types to write a more safe and expressive code.

-<p>Finally, I’d like to finish this post with one of my favorite quotes:</p> +

Finally, I’d like to finish this post with one of my favorite quotes:

-<blockquote> - <p>Well engineered solutions fail early, fail fast, fail often.</p> -</blockquote> +
+

Well engineered solutions fail early, fail fast, fail often.

+
-<p>Happy coding!</p>
Alex CorviFew days ago, I wrote mongots, an alternative API for MongoDB to make it work better with TypeScript (a strongly-typed language that compiles to JS) on the NodeJS environment.
Constructors and Destructors in C2017-10-25T05:00:00+00:002017-10-25T05:00:00+00:00/Constructors%20and%20Destructors%20in%20C<blockquote> - <p>Everything discussed here is a feature brought to you by the <a href="https://gcc.gnu.org/"><code class="language-plaintext highlighter-rouge">GCC</code></a> compiler. If you happen to be using a different compiler, I’m not sure all or any of this would apply given the fact that these features aren’t part of the <code class="language-plaintext highlighter-rouge">C</code> programming language per se.</p> -</blockquote> +

Happy coding!

]]>
Alex Corvi
Constructors and Destructors in C2017-10-25T05:00:00+00:002017-10-25T05:00:00+00:00/Constructors%20and%20Destructors%20in%20C +

Everything discussed here is a feature brought to you by the GCC compiler. If you happen to be using a different compiler, I’m not sure all or any of this would apply given the fact that these features aren’t part of the C programming language per se.

+ -<p>When writing programs of considerable size and complexity, we tend to modularize our code. That is, we try to think of all different components as objects that can be easily moved around and fit within existing and future code. In C, it’s common practice for developers to divide code into libraries and header files that can be included as needed. When working with someone else’s library, you’d normally rather have a getting-started document that’s as short and as concise as possible.</p> +

When writing programs of considerable size and complexity, we tend to modularize our code. That is, we try to think of all different components as objects that can be easily moved around and fit within existing and future code. In C, it’s common practice for developers to divide code into libraries and header files that can be included as needed. When working with someone else’s library, you’d normally rather have a getting-started document that’s as short and as concise as possible.

-<p>Let’s consider an example. You’re working with a team that’s responsible for implementing a stack data structure and is expected to hand you the five essential functions every stack should have: <code class="language-plaintext highlighter-rouge">push()</code>, <code class="language-plaintext highlighter-rouge">pop()</code>, <code class="language-plaintext highlighter-rouge">peek()</code>, <code class="language-plaintext highlighter-rouge">isFull()</code>, and <code class="language-plaintext highlighter-rouge">isEmpty()</code>. You’re probably already wondering “who’s going to initialize the stack? Do I have to? Will they hand me an initialized instance? Is it stack-allocated or heap-allocated? If it’s heap-allocated, do I have to worry about freeing it myself?” The stream of questions can literally be endless the more complex the library is. Wouldn’t it be better for the library to handle all the heavy lifting of having to instantiate all necessary data objects and do the housekeeping after itself when its job is finished (something of the nature of a constructor that’s called automatically once the library is included and a destructor that’s called when the library is done with)?</p> +

Let’s consider an example. You’re working with a team that’s responsible for implementing a stack data structure and is expected to hand you the five essential functions every stack should have: push(), pop(), peek(), isFull(), and isEmpty(). You’re probably already wondering “who’s going to initialize the stack? Do I have to? Will they hand me an initialized instance? Is it stack-allocated or heap-allocated? If it’s heap-allocated, do I have to worry about freeing it myself?” The stream of questions can literally be endless the more complex the library is. Wouldn’t it be better for the library to handle all the heavy lifting of having to instantiate all necessary data objects and do the housekeeping after itself when its job is finished (something of the nature of a constructor that’s called automatically once the library is included and a destructor that’s called when the library is done with)?

-<h2 id="constructors">Constructors</h2> +

Constructors

-<p>Let’s assume we have a header file named ‘stack.h’:</p> +

Let’s assume we have a header file named ‘stack.h’:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#ifndef STACK_H +
#ifndef STACK_H
 #define STACK_H
-</span>
-<span class="cp">#include &lt;stdio.h&gt;   // printf
-#include &lt;stdlib.h&gt;  // calloc &amp; free
-#include &lt;stdbool.h&gt; // true &amp; false
-</span>
-<span class="cp">#define STACK_CAP 12
-</span>
-<span class="kt">int</span><span class="o">*</span> <span class="n">stack</span><span class="p">;</span>
-<span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">stack_ptr</span><span class="p">;</span>
-
-<span class="n">bool</span> <span class="nf">isEmpty</span><span class="p">()</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="n">stack_ptr</span> <span class="o">==</span> <span class="mi">0</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="n">bool</span> <span class="nf">isFull</span><span class="p">()</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="n">stack_ptr</span> <span class="o">==</span> <span class="n">STACK_CAP</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="n">bool</span> <span class="nf">push</span><span class="p">(</span><span class="kt">int</span> <span class="n">val</span><span class="p">)</span> <span class="p">{</span>
-  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isFull</span><span class="p">())</span> <span class="p">{</span>
-    <span class="n">stack</span><span class="p">[</span><span class="n">stack_ptr</span><span class="o">++</span><span class="p">]</span> <span class="o">=</span> <span class="n">val</span><span class="p">;</span>
-    <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-  <span class="p">}</span>
-  <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="n">bool</span> <span class="nf">peek</span><span class="p">(</span><span class="kt">int</span><span class="o">*</span> <span class="n">ref</span><span class="p">)</span> <span class="p">{</span>
-  <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">isEmpty</span><span class="p">())</span> <span class="p">{</span>
-    <span class="o">*</span><span class="n">ref</span> <span class="o">=</span> <span class="n">stack</span><span class="p">[</span><span class="n">stack_ptr</span> <span class="o">-</span> <span class="mi">1</span><span class="p">];</span>
-    <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-  <span class="p">}</span>
-  <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="n">bool</span> <span class="nf">pop</span><span class="p">(</span><span class="kt">int</span><span class="o">*</span> <span class="n">ref</span><span class="p">)</span> <span class="p">{</span>
-  <span class="k">if</span> <span class="p">(</span><span class="n">peek</span><span class="p">(</span><span class="n">ref</span><span class="p">))</span> <span class="p">{</span>
-    <span class="n">stack_ptr</span><span class="o">--</span><span class="p">;</span>
-    <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-  <span class="p">}</span>
-  <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="cp">#endif
-</span></code></pre></div></div>
-
-<p>You’ve probably already noticed that <code class="language-plaintext highlighter-rouge">stack</code> and <code class="language-plaintext highlighter-rouge">stack_ptr</code> are left uninitialized, so if you were to blindly use <code class="language-plaintext highlighter-rouge">push</code>, <code class="language-plaintext highlighter-rouge">peek</code>, or <code class="language-plaintext highlighter-rouge">pop</code>, you’re going to run into a segmentation fault as <code class="language-plaintext highlighter-rouge">stack</code> is a <code class="language-plaintext highlighter-rouge">NULL</code> pointer, and <code class="language-plaintext highlighter-rouge">stack_ptr</code> is likely to contain some gibberish that was left behind on the stack. The proper way to use these functions would be to allocate memory for the <code class="language-plaintext highlighter-rouge">stack</code> pointer and <code class="language-plaintext highlighter-rouge">free</code> it when you’re done. An even better way to do this would be to have this task automatically preformed at the time of including this header file. This is done through a library constructor, and it’s done as follows:</p>
-
-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/*  Library Constructor
+
+#include <stdio.h>   // printf
+#include <stdlib.h>  // calloc & free
+#include <stdbool.h> // true & false
+
+#define STACK_CAP 12
+
+int* stack;
+unsigned int stack_ptr;
+
+bool isEmpty() {
+  return stack_ptr == 0;
+}
+
+bool isFull() {
+  return stack_ptr == STACK_CAP;
+}
+
+bool push(int val) {
+  if (!isFull()) {
+    stack[stack_ptr++] = val;
+    return true;
+  }
+  return false;
+}
+
+bool peek(int* ref) {
+  if (!isEmpty()) {
+    *ref = stack[stack_ptr - 1];
+    return true;
+  }
+  return false;
+}
+
+bool pop(int* ref) {
+  if (peek(ref)) {
+    stack_ptr--;
+    return true;
+  }
+  return false;
+}
+
+#endif
+
+ +

You’ve probably already noticed that stack and stack_ptr are left uninitialized, so if you were to blindly use push, peek, or pop, you’re going to run into a segmentation fault as stack is a NULL pointer, and stack_ptr is likely to contain some gibberish that was left behind on the stack. The proper way to use these functions would be to allocate memory for the stack pointer and free it when you’re done. An even better way to do this would be to have this task automatically preformed at the time of including this header file. This is done through a library constructor, and it’s done as follows:

+ +
/*  Library Constructor
     @Brief: This function is automatically called when
     the containing header file is included.
-*/</span>
-<span class="n">__attribute__</span><span class="p">((</span><span class="n">constructor</span><span class="p">))</span> <span class="kt">void</span> <span class="nf">start</span><span class="p">()</span> <span class="p">{</span>
-   <span class="n">printf</span><span class="p">(</span><span class="s">"Inside Constructor</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
-   <span class="n">stack_ptr</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
-   <span class="n">stack</span> <span class="o">=</span> <span class="p">(</span><span class="kt">int</span><span class="o">*</span><span class="p">)</span><span class="n">calloc</span><span class="p">(</span><span class="n">STACK_CAP</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">int</span><span class="p">));</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>The function above needs to be located inside your header file and will be automatically called once you’ve included the header file somewhere in your code.</p>
-
-<blockquote>
-  <p>In case you didn’t know, <code class="language-plaintext highlighter-rouge">#ifndef STACK_H</code>, <code class="language-plaintext highlighter-rouge">#define STACK_H</code> and <code class="language-plaintext highlighter-rouge">#endif</code> are needed to prevent multiple or recursive includes that’ll cause the compiler to run into redefinition issues.</p>
-</blockquote>
-
-<p>Now the following program:</p>
-
-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdio.h&gt;
-#include "header.h"
-</span>
-<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="n">printf</span><span class="p">(</span><span class="s">"Inside main</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
-    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>Will generate the following output:</p>
-
-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Inside Constructor
+*/
+__attribute__((constructor)) void start() {
+   printf("Inside Constructor\n");
+   stack_ptr = 0;
+   stack = (int*)calloc(STACK_CAP, sizeof(int));
+}
+
+ +

The function above needs to be located inside your header file and will be automatically called once you’ve included the header file somewhere in your code.

+ +
+

In case you didn’t know, #ifndef STACK_H, #define STACK_H and #endif are needed to prevent multiple or recursive includes that’ll cause the compiler to run into redefinition issues.

+
+ +

Now the following program:

+ +
#include <stdio.h>
+#include "header.h"
+
+int main() {
+    printf("Inside main\n");
+    return 0;
+}
+
+ +

Will generate the following output:

+ +
Inside Constructor
 Inside Main
-</code></pre></div></div>
+
-<p>And exit peacefully… Well not really peacefully. At least not in every sense of the word as your program has left some heap-allocated memory un-deallocated. You’re not likely going to see your program crash or anything, but you’ve still introduced a bug to your system that the OS may or may not be able to resolve depending on what OS you happen to be using. The proper way to go about programmatically solve this problem is to use a destructor in your application. A destructor is another function that gets called automatically once you’re done with the library. Read ahead to find out how this is done.</p> +

And exit peacefully… Well not really peacefully. At least not in every sense of the word as your program has left some heap-allocated memory un-deallocated. You’re not likely going to see your program crash or anything, but you’ve still introduced a bug to your system that the OS may or may not be able to resolve depending on what OS you happen to be using. The proper way to go about programmatically solve this problem is to use a destructor in your application. A destructor is another function that gets called automatically once you’re done with the library. Read ahead to find out how this is done.

-<h2 id="destructors">Destructors</h2> +

Destructors

-<p>You’re going to like this part.</p> +

You’re going to like this part.

-<p>We’ve used <code class="language-plaintext highlighter-rouge">__attribute__((constructor))</code> to introduce a constructor into our code, so you’re probably already thinking a <code class="language-plaintext highlighter-rouge">__attribute__((destructor))</code> is what we’d use to add a destructor, in which case you’d be absolutely right. Here’s our destructor function implementation for our stack library:</p> +

We’ve used __attribute__((constructor)) to introduce a constructor into our code, so you’re probably already thinking a __attribute__((destructor)) is what we’d use to add a destructor, in which case you’d be absolutely right. Here’s our destructor function implementation for our stack library:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/* Library Destructor +
/*  Library Destructor
     @Brief: This function is automatically called when
     the containing header file is dismissed (normally
     at the end of the program lifecycle).
-*/</span>
-<span class="n">__attribute__</span><span class="p">((</span><span class="n">destructor</span><span class="p">))</span> <span class="kt">void</span> <span class="nf">finish</span><span class="p">()</span> <span class="p">{</span>
-   <span class="n">printf</span><span class="p">(</span><span class="s">"Inside Destructor</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
-   <span class="n">free</span><span class="p">(</span><span class="n">stack</span><span class="p">);</span>
-   <span class="n">stack</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
-<span class="p">}</span>
-</code></pre></div></div>
+*/
+__attribute__((destructor)) void finish() {
+   printf("Inside Destructor\n");
+   free(stack);
+   stack = NULL;
+}
+
-<p>Now if you execute the same tiny program we’ve written above, you’ll get the following output:</p> +

Now if you execute the same tiny program we’ve written above, you’ll get the following output:

-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Inside Constructor +
Inside Constructor
 Inside Main
 Inside Destructor
-</code></pre></div></div>
+
-<p>And there we’ve achieved a library implementation that takes care of all necessary memory management for us.</p>
Fadi Hanna Al-KassEverything discussed here is a feature brought to you by the GCC compiler. If you happen to be using a different compiler, I’m not sure all or any of this would apply given the fact that these features aren’t part of the C programming language per se.
Remote Procedure Calls in C2017-10-22T05:00:00+00:002017-10-22T05:00:00+00:00/Remote%20Procedure%20Calls%20in%20C<p>I have recently put together a quick Remote Procedure Call (RPC) demo in C and checked it into <a href="https://github.com/Alkass/cRPC">my Github account</a>, then I realized I still have a couple of minutes left on my hands, so I decided to write a walk-through blog post.</p> +

And there we’ve achieved a library implementation that takes care of all necessary memory management for us.

]]>
Fadi Hanna Al-Kass
Remote Procedure Calls in C2017-10-22T05:00:00+00:002017-10-22T05:00:00+00:00/Remote%20Procedure%20Calls%20in%20CI have recently put together a quick Remote Procedure Call (RPC) demo in C and checked it into my Github account, then I realized I still have a couple of minutes left on my hands, so I decided to write a walk-through blog post.

-<p>Remote Procedure Calls, if you’re not familiar with them, are library implementations that allow you to remotely host some code (normally in the form of classes and functions) and invoke those classes and functions as needed.</p> +

Remote Procedure Calls, if you’re not familiar with them, are library implementations that allow you to remotely host some code (normally in the form of classes and functions) and invoke those classes and functions as needed.

-<p>Why would you ever want to do that? I mean, what benefit do you get from having pieces of your code run on a remote server? There actually are a number of valid reasons why that would be the case, but I’m only interested in addressing two as I don’t want to run off topic. One reason is performance. Say a mobile app you’ve been writing requires high processing power availability to compute some complex mathematical equations. Most mobile devices aren’t meant to be cutting-edge processing devices that are able to scale up to any task you hand to them. In a case like this, you’d probably better off hand the calculation task to a more processing-ready device and ask for the results since that’s all you’re really interested in. Another reason is security. If you’re developing a banking solution, for instance, chances are you want to make it as hard as possible for reverse engineers to hack into your code and find out how deposits, withdraws, and transactions are made. RPCs are a viable option here.</p> +

Why would you ever want to do that? I mean, what benefit do you get from having pieces of your code run on a remote server? There actually are a number of valid reasons why that would be the case, but I’m only interested in addressing two as I don’t want to run off topic. One reason is performance. Say a mobile app you’ve been writing requires high processing power availability to compute some complex mathematical equations. Most mobile devices aren’t meant to be cutting-edge processing devices that are able to scale up to any task you hand to them. In a case like this, you’d probably better off hand the calculation task to a more processing-ready device and ask for the results since that’s all you’re really interested in. Another reason is security. If you’re developing a banking solution, for instance, chances are you want to make it as hard as possible for reverse engineers to hack into your code and find out how deposits, withdraws, and transactions are made. RPCs are a viable option here.

-<p>Now onto some technical stuff…</p> +

Now onto some technical stuff…

-<p>If you’ve ever written TCP-based projects in your life, chances are you’ve serialized data at one end and deserialized it at the other end. Serialization often takes the form of a string that is supposedly safe to parse. If you’re a performance rat like myself, you’re probably seeing a problem already. String parsing is expensive and error prone. Having to parse a string on the fly means more code, more code (in most cases) means (1) slower code and (2) more possible bugs. More bugs means more time on debugging and less on productivity. You see where I’m going with this.</p> +

If you’ve ever written TCP-based projects in your life, chances are you’ve serialized data at one end and deserialized it at the other end. Serialization often takes the form of a string that is supposedly safe to parse. If you’re a performance rat like myself, you’re probably seeing a problem already. String parsing is expensive and error prone. Having to parse a string on the fly means more code, more code (in most cases) means (1) slower code and (2) more possible bugs. More bugs means more time on debugging and less on productivity. You see where I’m going with this.

-<p>What I’d suggest as a better alternative is communicating through a stream of bytes that conform to a set of standards.</p> +

What I’d suggest as a better alternative is communicating through a stream of bytes that conform to a set of standards.

-<p>Say you’re building a remote controlled calculator with the most four basic operations (addition, subtraction, multiplication, and division). Now to be honest, I don’t know why you’d ever want to build this calculator. That’d be stupid. But for the sake of clarity, I couldn’t have thought of an easier example.</p> +

Say you’re building a remote controlled calculator with the most four basic operations (addition, subtraction, multiplication, and division). Now to be honest, I don’t know why you’d ever want to build this calculator. That’d be stupid. But for the sake of clarity, I couldn’t have thought of an easier example.

-<p>To properly send a request to your server, you’ll need to have an agreement on a request standard. Our request standard can be implemented as a <code class="language-plaintext highlighter-rouge">C</code> <code class="language-plaintext highlighter-rouge">struct</code> with a pre-determined number of bytes. All requests sent to the server must be fit within this number of byte count so the server will always know how many bytes to read at a time that make up a single request.</p> +

To properly send a request to your server, you’ll need to have an agreement on a request standard. Our request standard can be implemented as a C struct with a pre-determined number of bytes. All requests sent to the server must be fit within this number of byte count so the server will always know how many bytes to read at a time that make up a single request.

-<p>Before we implement our <code class="language-plaintext highlighter-rouge">Request</code> <code class="language-plaintext highlighter-rouge">struct</code>, let’s first decide what fields we need to include.</p> +

Before we implement our Request struct, let’s first decide what fields we need to include.

-<p>What we could do is always start with a conventional acknowledgment byte that helps both the server and the client decide whether the number of bytes read make up a valid request/response to be processed. This is extremely useful when debugging cases when one side of your project starts to misbehave, then you could do some debugging and make sure outgoing requests or incoming responses are valid by checking against the acknowledgment byte. We shall call this field <code class="language-plaintext highlighter-rouge">ack</code> for ease of writing.</p> +

What we could do is always start with a conventional acknowledgment byte that helps both the server and the client decide whether the number of bytes read make up a valid request/response to be processed. This is extremely useful when debugging cases when one side of your project starts to misbehave, then you could do some debugging and make sure outgoing requests or incoming responses are valid by checking against the acknowledgment byte. We shall call this field ack for ease of writing.

-<p>Another useful field we could include is a request identifier. Identifiers are useful in cases when the client isn’t reading the responses right away and may have difficulty telling the responses apart. What we could do here is include the identifier as part of the response we send back as a server.</p> +

Another useful field we could include is a request identifier. Identifiers are useful in cases when the client isn’t reading the responses right away and may have difficulty telling the responses apart. What we could do here is include the identifier as part of the response we send back as a server.

-<p>Our third field will be the operation field. This field tells us what function the user wants to execute.</p> +

Our third field will be the operation field. This field tells us what function the user wants to execute.

-<p>We’ll also need two fields for the parameters.</p> +

We’ll also need two fields for the parameters.

-<p>Sounds about it!</p> +

Sounds about it!

-<p>Now, 1 field for <code class="language-plaintext highlighter-rouge">ack</code>, 1 for <code class="language-plaintext highlighter-rouge">id</code>, 1 for <code class="language-plaintext highlighter-rouge">op</code> and 2 for <code class="language-plaintext highlighter-rouge">params</code> add up to 5 bytes. Every time the server attempts to read a request, it’ll read exactly 5 bytes.</p> +

Now, 1 field for ack, 1 for id, 1 for op and 2 for params add up to 5 bytes. Every time the server attempts to read a request, it’ll read exactly 5 bytes.

-<p>Our <code class="language-plaintext highlighter-rouge">strcut</code> will look like so:</p> +

Our strcut will look like so:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span> - <span class="kt">char</span> <span class="n">ack</span><span class="p">;</span> - <span class="kt">char</span> <span class="n">id</span><span class="p">;</span> - <span class="kt">char</span> <span class="n">op</span><span class="p">;</span> - <span class="kt">char</span> <span class="n">params</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span> -<span class="p">}</span> <span class="n">Request</span><span class="p">;</span> -</code></pre></div></div> +
typedef struct {
+  char ack;
+  char id;
+  char op;
+  char params[2];
+} Request;
+
-<p>Characters in <code class="language-plaintext highlighter-rouge">C</code> are 1 byte (8-bit) integers. because <code class="language-plaintext highlighter-rouge">byte</code> isn’t a valid data type in <code class="language-plaintext highlighter-rouge">C</code>, we can type-define it as follows:</p> +

Characters in C are 1 byte (8-bit) integers. because byte isn’t a valid data type in C, we can type-define it as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="kt">char</span> <span class="n">byte</span><span class="p">;</span> -</code></pre></div></div> +
typedef char byte;
+
-<p>and use it as so:</p> +

and use it as so:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span> - <span class="n">byte</span> <span class="n">ack</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">id</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">op</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">params</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span> -<span class="p">}</span> <span class="n">Request</span><span class="p">;</span> -</code></pre></div></div> +
typedef struct {
+  byte ack;
+  byte id;
+  byte op;
+  byte params[2];
+} Request;
+
-<p>Our acknowledgment byte is consensual between the server and the client. We’ll make it 10 and set it as follows:</p> +

Our acknowledgment byte is consensual between the server and the client. We’ll make it 10 and set it as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#define ACK 0xA -</span></code></pre></div></div> +
#define ACK 0xA
+
-<p>Our operations can be part of an <code class="language-plaintext highlighter-rouge">OpType</code> <code class="language-plaintext highlighter-rouge">enum</code> as follows:</p> +

Our operations can be part of an OpType enum as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">enum</span> <span class="p">{</span> - <span class="n">ADD</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> - <span class="n">SUB</span><span class="p">,</span> - <span class="n">MUL</span><span class="p">,</span> - <span class="n">DIV</span> -<span class="p">}</span> <span class="n">OpType</span><span class="p">;</span> -</code></pre></div></div> +
typedef enum {
+  ADD = 0,
+  SUB,
+  MUL,
+  DIV
+} OpType;
+
-<p>Which allows us to replace the <code class="language-plaintext highlighter-rouge">byte</code> type in our <code class="language-plaintext highlighter-rouge">Request</code> <code class="language-plaintext highlighter-rouge">struct</code> with <code class="language-plaintext highlighter-rouge">OpType</code>, except we’ll run into a problem that is <code class="language-plaintext highlighter-rouge">enums</code> in <code class="language-plaintext highlighter-rouge">C</code> are of type integer (4-bytes long), but this issue can be overcome by enabling the <code class="language-plaintext highlighter-rouge">-fshort-enums</code> <code class="language-plaintext highlighter-rouge">GCC</code> switch that reduces the size of enums to 1 byte. Now we can re-write our <code class="language-plaintext highlighter-rouge">Request</code> <code class="language-plaintext highlighter-rouge">struct</code> as follows:</p> +

Which allows us to replace the byte type in our Request struct with OpType, except we’ll run into a problem that is enums in C are of type integer (4-bytes long), but this issue can be overcome by enabling the -fshort-enums GCC switch that reduces the size of enums to 1 byte. Now we can re-write our Request struct as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span> - <span class="n">byte</span> <span class="n">ack</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">id</span><span class="p">;</span> - <span class="n">OpType</span> <span class="n">op</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">params</span><span class="p">[</span><span class="mi">2</span><span class="p">];</span> -<span class="p">}</span> <span class="n">Request</span><span class="p">;</span> -</code></pre></div></div> +
typedef struct {
+  byte ack;
+  byte id;
+  OpType op;
+  byte params[2];
+} Request;
+
-<p>Now let’s define our <code class="language-plaintext highlighter-rouge">Response</code> <code class="language-plaintext highlighter-rouge">struct</code>.</p> +

Now let’s define our Response struct.

-<p>We’ll need a starting acknowledgment byte, so that’s one.</p> +

We’ll need a starting acknowledgment byte, so that’s one.

-<p>We’ll also need to include the request identifier. That’s two.</p> +

We’ll also need to include the request identifier. That’s two.

-<p>Not every request sent to the server is a valid request. The user may be requesting a functionality that has not been yet implemented or does not exist. For this, we could include a status field that helps the client decide whether the request was handled successfully.</p> +

Not every request sent to the server is a valid request. The user may be requesting a functionality that has not been yet implemented or does not exist. For this, we could include a status field that helps the client decide whether the request was handled successfully.

-<p>If the request is handled successfully, we’ll need to return some data to the user. We’ll need a data field to contain the result.</p> +

If the request is handled successfully, we’ll need to return some data to the user. We’ll need a data field to contain the result.

-<p>That adds up to four bytes. Here’s what our <code class="language-plaintext highlighter-rouge">Response</code> object will look like:</p> +

That adds up to four bytes. Here’s what our Response object will look like:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span> - <span class="n">byte</span> <span class="n">ack</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">id</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">status</span><span class="p">;</span> - <span class="n">byte</span> <span class="n">data</span><span class="p">;</span> -<span class="p">}</span> <span class="n">Response</span><span class="p">;</span> -</code></pre></div></div> +
typedef struct {
+  byte ack;
+  byte id;
+  byte status;
+  byte data;
+} Response;
+
-<p>Now assume you have a server up and running waiting to process some requests. You’d declare a <code class="language-plaintext highlighter-rouge">Request</code> object and <code class="language-plaintext highlighter-rouge">Response</code> object as follows:</p> +

Now assume you have a server up and running waiting to process some requests. You’d declare a Request object and Response object as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Request</span> <span class="n">req</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span> -<span class="n">Response</span> <span class="n">res</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span> -</code></pre></div></div> +
Request req  = {0};
+Response res = {0};
+
-<blockquote> - <p>The <code class="language-plaintext highlighter-rouge">{0}</code> is syntactic sugar that tells the compiler to set all values within the structure to zero.</p> -</blockquote> +
+

The {0} is syntactic sugar that tells the compiler to set all values within the structure to zero.

+
-<p>You’d then be reading the request as follows:</p> +

You’d then be reading the request as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">read</span><span class="p">(</span><span class="n">comm_fd</span><span class="p">,</span> <span class="p">(</span><span class="n">byte</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">req</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">Request</span><span class="p">));</span> -</code></pre></div></div> +
read(comm_fd, (byte*)&req, sizeof(Request));
+
-<blockquote> - <p>The <code class="language-plaintext highlighter-rouge">(byte*)&amp;req</code> typecasts our <code class="language-plaintext highlighter-rouge">Request</code> struct into a byte pointer.</p> -</blockquote> +
+

The (byte*)&req typecasts our Request struct into a byte pointer.

+
-<p>After a so number of bytes (5 in our case) has been read and converted to a <code class="language-plaintext highlighter-rouge">Request</code> object, we can go ahead and verify that the request is valid by checking against our consensual acknowledgment byte as follows:</p> +

After a so number of bytes (5 in our case) has been read and converted to a Request object, we can go ahead and verify that the request is valid by checking against our consensual acknowledgment byte as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">req</span><span class="p">.</span><span class="n">ack</span> <span class="o">==</span> <span class="n">ACK</span><span class="p">)</span> <span class="p">{</span> - <span class="c1">// Request is successful. Move forward</span> -<span class="p">}</span> -</code></pre></div></div> +
if (req.ack == ACK) {
+  // Request is successful. Move forward
+}
+
-<p>The first thing we could do is prepare the <code class="language-plaintext highlighter-rouge">ack</code> and <code class="language-plaintext highlighter-rouge">id</code> fields in our Response object as follows:</p> +

The first thing we could do is prepare the ack and id fields in our Response object as follows:

-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">res</span><span class="p">.</span><span class="n">ack</span> <span class="o">=</span> <span class="n">req</span><span class="p">.</span><span class="n">ack</span><span class="p">;</span> -<span class="n">res</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">req</span><span class="p">.</span><span class="n">id</span><span class="p">;</span> -</code></pre></div></div> +
res.ack = req.ack;
+res.id = req.id;
+
-<p>Then call a <code class="language-plaintext highlighter-rouge">handleRequest</code> function that’s responsible for handling the request and handing back the data. This function (and its callees) are implemented as follows:</p> - -<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">int</span> <span class="nf">handleAdd</span><span class="p">(</span><span class="k">const</span> <span class="n">Request</span><span class="o">*</span> <span class="n">req</span><span class="p">,</span> <span class="n">Response</span><span class="o">*</span> <span class="n">res</span><span class="p">)</span> <span class="p">{</span> - <span class="n">printf</span><span class="p">(</span><span class="s">"res-&gt;data = %d + %d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span> - <span class="n">res</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span> - <span class="k">return</span> <span class="nb">true</span><span class="p">;</span> -<span class="p">}</span> +

Then call a handleRequest function that’s responsible for handling the request and handing back the data. This function (and its callees) are implemented as follows:

+ +
int handleAdd(const Request* req, Response* res) {
+  printf("res->data = %d + %d\n", req->params[0], req->params[1]);
+  res->data = req->params[0] + req->params[1];
+  return true;
+}
 
-<span class="kt">int</span> <span class="nf">handleSub</span><span class="p">(</span><span class="k">const</span> <span class="n">Request</span><span class="o">*</span> <span class="n">req</span><span class="p">,</span> <span class="n">Response</span><span class="o">*</span> <span class="n">res</span><span class="p">)</span> <span class="p">{</span>
-  <span class="n">printf</span><span class="p">(</span><span class="s">"res-&gt;data = %d - %d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
-  <span class="n">res</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
-  <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="kt">int</span> <span class="nf">handleMul</span><span class="p">(</span><span class="k">const</span> <span class="n">Request</span><span class="o">*</span> <span class="n">req</span><span class="p">,</span> <span class="n">Response</span><span class="o">*</span> <span class="n">res</span><span class="p">)</span> <span class="p">{</span>
-  <span class="n">printf</span><span class="p">(</span><span class="s">"res-&gt;data = %d * %d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
-  <span class="n">res</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
-  <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="kt">int</span> <span class="nf">handleDiv</span><span class="p">(</span><span class="k">const</span> <span class="n">Request</span><span class="o">*</span> <span class="n">req</span><span class="p">,</span> <span class="n">Response</span><span class="o">*</span> <span class="n">res</span><span class="p">)</span> <span class="p">{</span>
-  <span class="n">printf</span><span class="p">(</span><span class="s">"res-&gt;data = %d / %d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
-  <span class="n">res</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">/</span> <span class="n">req</span><span class="o">-&gt;</span><span class="n">params</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
-  <span class="k">return</span> <span class="nb">true</span><span class="p">;</span>
-<span class="p">}</span>
-
-<span class="kt">int</span> <span class="nf">handleRequest</span><span class="p">(</span><span class="k">const</span> <span class="n">Request</span><span class="o">*</span> <span class="n">req</span><span class="p">,</span> <span class="n">Response</span><span class="o">*</span> <span class="n">res</span><span class="p">)</span> <span class="p">{</span>
-  <span class="k">switch</span> <span class="p">(</span><span class="n">req</span><span class="o">-&gt;</span><span class="n">op</span><span class="p">)</span> <span class="p">{</span>
-    <span class="k">case</span> <span class="n">ADD</span><span class="p">:</span>
-      <span class="k">return</span> <span class="n">handleAdd</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">res</span><span class="p">);</span>
-    <span class="k">case</span> <span class="n">SUB</span><span class="p">:</span>
-      <span class="k">return</span> <span class="n">handleSub</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">res</span><span class="p">);</span>
-    <span class="k">case</span> <span class="n">MUL</span><span class="p">:</span>
-      <span class="k">return</span> <span class="n">handleMul</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">res</span><span class="p">);</span>
-    <span class="k">case</span> <span class="n">DIV</span><span class="p">:</span>
-      <span class="k">return</span> <span class="n">handleDiv</span><span class="p">(</span><span class="n">req</span><span class="p">,</span> <span class="n">res</span><span class="p">);</span>
-    <span class="nl">default:</span>
-      <span class="k">return</span> <span class="nb">false</span><span class="p">;</span>
-  <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And can be called as follows:</p>
-
-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">handleRequest</span><span class="p">(</span><span class="o">&amp;</span><span class="n">req</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">res</span><span class="p">))</span> <span class="p">{</span>
-  <span class="n">res</span><span class="p">.</span><span class="n">status</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
-<span class="p">}</span>
-<span class="k">else</span> <span class="p">{</span>
-  <span class="n">res</span><span class="p">.</span><span class="n">status</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>The response can be sent to the client as follows:</p>
-
-<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">write</span><span class="p">(</span><span class="n">comm_fd</span><span class="p">,</span> <span class="p">(</span><span class="n">byte</span><span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">res</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">Response</span><span class="p">));</span>
-</code></pre></div></div>
-
-<p>And there we have a fully functional RPC server implementation capable of performing just about anything when expanded.</p>
-
-<blockquote>
-  <p>The demo I referred to at the beginning of this post can be found <a href="https://github.com/Alkass/cRPC">here</a></p>
-</blockquote>Fadi Hanna Al-KassI have recently put together a quick Remote Procedure Call (RPC) demo in C and checked it into my Github account, then I realized I still have a couple of minutes left on my hands, so I decided to write a walk-through blog post.Crafting Code - Building Common Interfaces2017-06-20T05:00:00+00:002017-06-20T05:00:00+00:00/Crafting%20Code%201<p>When writing libraries, APIs, and SDKs, the less stuff you ask your user to memorize the better it looks to you and feels to them. For instance, if you were to write a Math library that performs some arithmetic operations, you could write your library functions as so:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">add</span><span class="p">(</span><span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="n">op1</span> <span class="o">+</span> <span class="n">op2</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">sub</span><span class="p">(</span><span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="n">op1</span> <span class="o">-</span> <span class="n">op2</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">mul</span><span class="p">(</span><span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="n">op1</span> <span class="o">*</span> <span class="n">op2</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">div</span><span class="p">(</span><span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="n">op1</span> <span class="o">/</span> <span class="n">op2</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And that’ll require the user to import his/her desired function or set of functions as needed. This is fine, but wouldn’t it be better if you could provide only one function that does all these operations? We’re going to call this function a common interface, but this procedure is called a passthrough in the professional field. A passthrough function is a multi-purpose entry point to a set of different classes or functions. In the case of our Math library, we could have our passthrough function written as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">passthrough</span><span class="p">(</span><span class="n">operation</span><span class="p">:</span> <span class="o">&amp;</span><span class="nv">'static</span> <span class="nb">str</span><span class="p">,</span> <span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="k">match</span> <span class="n">operation</span> <span class="p">{</span>
-    <span class="s">"+"</span> <span class="k">=&gt;</span> <span class="nf">add</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="s">"-"</span> <span class="k">=&gt;</span> <span class="nf">sub</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="s">"*"</span> <span class="k">=&gt;</span> <span class="nf">mul</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="s">"/"</span> <span class="k">=&gt;</span> <span class="nf">div</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="mi">_</span> <span class="k">=&gt;</span> <span class="mi">0</span> <span class="k">as</span> <span class="nb">f32</span><span class="p">,</span> <span class="c">//Return 0 if unknown operation. Near future bug alert!!!</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>That allows us to do something like this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">passthrough</span><span class="p">(</span><span class="s">"+"</span><span class="p">,</span> <span class="mi">10</span> <span class="k">as</span> <span class="nb">f32</span><span class="p">,</span> <span class="mf">12.3</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>Instead of this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">add</span><span class="p">(</span><span class="mf">32.4</span><span class="p">,</span> <span class="mi">12</span> <span class="k">as</span> <span class="nb">f32</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>But there’s more we could do here. So, for instance, instead of specifying the operation as a string and expose our code to all sorts of correctness bugs (afterall, our <code class="language-plaintext highlighter-rouge">passthrough()</code> function won’t warn us about an invalid operation), we could do something like this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">enum</span> <span class="n">OperationType</span> <span class="p">{</span>
-    <span class="n">ADD</span><span class="p">,</span>
-    <span class="n">SUB</span><span class="p">,</span>
-    <span class="n">MUL</span><span class="p">,</span>
-    <span class="n">DIV</span><span class="p">,</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">passthrough</span><span class="p">(</span><span class="n">operation</span><span class="p">:</span> <span class="n">OperationType</span><span class="p">,</span> <span class="n">op1</span><span class="p">:</span> <span class="nb">f32</span><span class="p">,</span> <span class="n">op2</span><span class="p">:</span> <span class="nb">f32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="k">match</span> <span class="n">operation</span> <span class="p">{</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">ADD</span> <span class="k">=&gt;</span> <span class="nf">add</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">SUB</span> <span class="k">=&gt;</span> <span class="nf">sub</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">MUL</span> <span class="k">=&gt;</span> <span class="nf">mul</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">DIV</span> <span class="k">=&gt;</span> <span class="nf">div</span><span class="p">(</span><span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">),</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>That will at least force the user to select one of many options, and anything that’s not on the list won’t slide. But that’s not all either. There’s still more that can be done to tweak our code.</p>
-
-<p>Notice how <code class="language-plaintext highlighter-rouge">passthrough</code> will always take two operands, no more or less parameters. What if, in the future, you decide to add an operation that requires only one operand (a square root function for example). You may be able to get away with something as easy as <code class="language-plaintext highlighter-rouge">passthrough(OperationType::SQRT, 25, 0)</code>, but that neither looks clean nor is something a team of professional developers would approve of. Perhaps we could turn our operands into a flexible object, and for the sake of simplicity we shall call our object <code class="language-plaintext highlighter-rouge">Request</code> and have it implemented as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">enum</span> <span class="n">Request</span> <span class="p">{</span>
-    <span class="n">NoOps</span><span class="p">,</span>
-    <span class="nf">OneOp</span><span class="p">(</span><span class="nb">f32</span><span class="p">),</span>
-    <span class="nf">TwoOps</span><span class="p">(</span><span class="nb">f32</span><span class="p">,</span> <span class="nb">f32</span><span class="p">),</span>
-    <span class="nf">ThreeOps</span><span class="p">(</span><span class="nb">f32</span><span class="p">,</span> <span class="nb">f32</span><span class="p">,</span> <span class="nb">f32</span><span class="p">),</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And re-implement our <code class="language-plaintext highlighter-rouge">passthrough()</code> function to work with a <code class="language-plaintext highlighter-rouge">Request</code> object as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">passthrough</span><span class="p">(</span><span class="n">operation</span><span class="p">:</span> <span class="n">OperationType</span><span class="p">,</span> <span class="n">req</span><span class="p">:</span> <span class="n">Request</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="k">match</span> <span class="n">operation</span> <span class="p">{</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">ADD</span> <span class="k">=&gt;</span> <span class="nf">add</span><span class="p">(</span><span class="n">req</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">SUB</span> <span class="k">=&gt;</span> <span class="nf">sub</span><span class="p">(</span><span class="n">req</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">MUL</span> <span class="k">=&gt;</span> <span class="nf">mul</span><span class="p">(</span><span class="n">req</span><span class="p">),</span>
-    <span class="nn">OperationType</span><span class="p">::</span><span class="n">DIV</span> <span class="k">=&gt;</span> <span class="nf">div</span><span class="p">(</span><span class="n">req</span><span class="p">),</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And re-implement our arithmetic functions to use our <code class="language-plaintext highlighter-rouge">Request</code> object instead of straight operands:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">add</span><span class="p">(</span><span class="n">req</span><span class="p">:</span> <span class="n">Request</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">f32</span> <span class="p">{</span>
-  <span class="k">return</span> <span class="k">match</span> <span class="n">req</span> <span class="p">{</span>
-    <span class="nn">Request</span><span class="p">::</span><span class="n">NoOps</span> <span class="k">=&gt;</span> <span class="mi">0</span> <span class="k">as</span> <span class="nb">f32</span><span class="p">,</span>
-    <span class="nn">Request</span><span class="p">::</span><span class="nf">OneOp</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="n">a</span><span class="p">,</span><span class="n">w</span>
-    <span class="nn">Request</span><span class="p">::</span><span class="nf">TwoOps</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">,</span>
-    <span class="nn">Request</span><span class="p">::</span><span class="nf">ThreeOps</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">c</span><span class="p">,</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And the resulting code will then allow us to do something like this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">passthrough</span><span class="p">(</span><span class="nn">OperationType</span><span class="p">::</span><span class="n">ADD</span><span class="p">,</span> <span class="nn">Request</span><span class="p">::</span><span class="n">NoOps</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>Or this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">passthrough</span><span class="p">(</span><span class="nn">OperationType</span><span class="p">::</span><span class="n">ADD</span><span class="p">,</span> <span class="nn">Request</span><span class="p">::</span><span class="nf">TwoOps</span><span class="p">(</span><span class="mf">10.1</span><span class="p">,</span> <span class="mf">40.5</span><span class="p">));</span>
-</code></pre></div></div>
-
-<p>Or this:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">passthrough</span><span class="p">(</span><span class="nn">OperationType</span><span class="p">::</span><span class="n">ADD</span><span class="p">,</span> <span class="nn">Request</span><span class="p">::</span><span class="nf">ThreeOps</span><span class="p">(</span><span class="mf">10.1</span><span class="p">,</span> <span class="mf">40.5</span><span class="p">));</span>
-</code></pre></div></div>
-
-<p>There’s still more room for improvement, but you get the point.</p>
-
-<p>So, “why should I consider a passthrough design?”, you may wonder! Here are some reasons why:</p>
-
-<ul>
-  <li>
-    <p>Passthroughs allow you to completely maintain your own code when working with a team of developers. That is to say your code needs not be scattered around, nor will anyone need direct access to any of your functions; you make your inner functions private, provide a <code class="language-plaintext highlighter-rouge">passthrough</code> function and there you roll ^_^.</p>
-  </li>
-  <li>
-    <p>Documentation becomes a breeze. Think about it. Instead of having to document every single function and provide snippets and use cases, you can keep all these functions private and only worry about documenting one: your <code class="language-plaintext highlighter-rouge">passthrough()</code> function. This can save you lots and lots of time.</p>
-  </li>
-</ul>Fadi Hanna Al-KassWhen writing libraries, APIs, and SDKs, the less stuff you ask your user to memorize the better it looks to you and feels to them. For instance, if you were to write a Math library that performs some arithmetic operations, you could write your library functions as so:Enum and Match Systems in Rust2017-06-17T05:00:00+00:002017-06-17T05:00:00+00:00/Enum%20and%20Match%20Systems%20in%20Rust<p>You’ve probably worked with <code class="language-plaintext highlighter-rouge">enums</code> before, but if you haven’t, they’re basically a way to have a selection out of a number of different options. A <code class="language-plaintext highlighter-rouge">Person</code> struct could contain a <code class="language-plaintext highlighter-rouge">gender</code> field that points to an enum of three options (<code class="language-plaintext highlighter-rouge">Male</code>, <code class="language-plaintext highlighter-rouge">Female</code>, and <code class="language-plaintext highlighter-rouge">Undisclosed</code>), i.e.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">enum</span> <span class="n">PersonGender</span> <span class="p">{</span>
-    <span class="n">MALE</span><span class="p">,</span>
-    <span class="n">FEMALE</span><span class="p">,</span>
-    <span class="n">UNDISCLOSED</span><span class="p">,</span>
-  <span class="p">}</span>
-
-  <span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span>
-    <span class="n">name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
-    <span class="n">age</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>
-    <span class="n">gender</span><span class="p">:</span> <span class="n">PersonGender</span><span class="p">,</span>
-  <span class="p">}</span>
-
-  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-      <span class="n">name</span><span class="p">:</span> <span class="s">"Fadi Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">(),</span>
-      <span class="n">age</span><span class="p">:</span> <span class="mi">27</span><span class="p">,</span>
-      <span class="n">gender</span><span class="p">:</span> <span class="nn">PersonGender</span><span class="p">::</span><span class="n">MALE</span><span class="p">,</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Now, what if a person so chooses to identify as something else? In that case, you could add a 4th option (<code class="language-plaintext highlighter-rouge">Other</code>) and attach a value of type <code class="language-plaintext highlighter-rouge">String</code> to it. Here’s what your end result would look like:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">enum</span> <span class="n">PersonGender</span> <span class="p">{</span>
-    <span class="n">MALE</span><span class="p">,</span>
-    <span class="n">FEMALE</span><span class="p">,</span>
-    <span class="n">UNDISCLOSED</span><span class="p">,</span>
-    <span class="nf">OTHER</span><span class="p">(</span><span class="nb">String</span><span class="p">),</span>
-  <span class="p">}</span>
-
-  <span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span>
-    <span class="n">name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
-    <span class="n">age</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>
-    <span class="n">gender</span><span class="p">:</span> <span class="n">PersonGender</span><span class="p">,</span>
-  <span class="p">}</span>
-
-  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-      <span class="n">name</span><span class="p">:</span> <span class="s">"Jake Smith"</span><span class="nf">.to_string</span><span class="p">(),</span>
-      <span class="n">age</span><span class="p">:</span> <span class="mi">27</span><span class="p">,</span>
-      <span class="n">gender</span><span class="p">:</span> <span class="nn">PersonGender</span><span class="p">::</span><span class="nf">OTHER</span><span class="p">(</span><span class="s">"Agender"</span><span class="nf">.to_string</span><span class="p">()),</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Of course <code class="language-plaintext highlighter-rouge">enums</code> don’t have to be part of a struct, and <code class="language-plaintext highlighter-rouge">enum</code> values don’t have to be primitives either. An <code class="language-plaintext highlighter-rouge">enum</code> value can point to a <code class="language-plaintext highlighter-rouge">struct</code> or even another <code class="language-plaintext highlighter-rouge">enum</code> and so on. For instance, you can write a function that returns a status that’s either <code class="language-plaintext highlighter-rouge">PASS</code> or <code class="language-plaintext highlighter-rouge">FAILURE</code>. <code class="language-plaintext highlighter-rouge">PASS</code> can include a string while <code class="language-plaintext highlighter-rouge">FAILURE</code> can contain more information about the severity of the failure. This functionality can be achieved as so:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">enum</span> <span class="n">SeverityStatus</span> <span class="p">{</span>
-    <span class="nf">BENIGN</span><span class="p">(</span><span class="nb">String</span><span class="p">),</span>
-    <span class="nf">FATAL</span><span class="p">(</span><span class="nb">String</span><span class="p">),</span>
-  <span class="p">}</span>
-
-  <span class="k">enum</span> <span class="n">FunctionStatus</span> <span class="p">{</span>
-    <span class="nf">PASS</span><span class="p">(</span><span class="nb">String</span><span class="p">),</span>
-    <span class="nf">FAILURE</span><span class="p">(</span><span class="n">SeverityStatus</span><span class="p">),</span>
-  <span class="p">}</span>
-
-  <span class="k">fn</span> <span class="nf">compute_results</span><span class="p">()</span> <span class="k">-&gt;</span> <span class="n">FunctionStatus</span> <span class="p">{</span>
-    <span class="c">// Successful execution would look like the following:</span>
-    <span class="c">// return FunctionStatus::PASS("Everything looks good".to_string());</span>
-
-    <span class="c">// While a failure would be indicated as follows:</span>
-    <span class="k">return</span> <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">FAILURE</span><span class="p">(</span><span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">FATAL</span><span class="p">(</span><span class="s">"Continuing beyond this point will cause more damage to the hardware"</span><span class="nf">.to_string</span><span class="p">()));</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Now onto <code class="language-plaintext highlighter-rouge">match</code>. One of the things I love the most about <code class="language-plaintext highlighter-rouge">match</code> is its ability to unstructure objects. Let’s take a second look at our last code snippet and see how we can possibly handle the response coming back to us from <code class="language-plaintext highlighter-rouge">compute_results()</code>. For this, I’d definitely use a set of <code class="language-plaintext highlighter-rouge">match</code> statements, e.g.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">compute_results</span><span class="p">();</span>
-    <span class="k">match</span> <span class="n">res</span> <span class="p">{</span>
-      <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">PASS</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="c">// Handling a PASS response</span>
-        <span class="nd">println!</span><span class="p">(</span><span class="s">"PASS: {}"</span><span class="p">,</span> <span class="n">x</span><span class="p">);</span>
-      <span class="p">}</span>
-      <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">FAILURE</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="c">// Handling a FAILURE response</span>
-        <span class="k">match</span> <span class="n">x</span> <span class="p">{</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">BENIGN</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="c">// Handling a BENIGN FAILURE response</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"BENIGN: {}"</span><span class="p">,</span> <span class="n">y</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">FATAL</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="c">// Handling a FATAL FAILURE response</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"FATAL: {}"</span><span class="p">,</span> <span class="n">y</span><span class="p">);</span>
-          <span class="p">}</span>
-        <span class="p">};</span>
-      <span class="p">}</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Now, if you happen to add more options to any of the two <code class="language-plaintext highlighter-rouge">enums</code> (say, a <code class="language-plaintext highlighter-rouge">WARN</code> option to <code class="language-plaintext highlighter-rouge">FunctionStatus</code> or <code class="language-plaintext highlighter-rouge">UNCATEGORIZED</code> to <code class="language-plaintext highlighter-rouge">SeverityStatus</code>), the compiler will refuse to compile your code until all possible cases are handled. This is definitely a plus as it forces you to think about all the paths your code could take.</p>
-
-<p>However, there will be times when you really only want to handle specific cases and not the rest. For instance, we may only be interested in handling the case of failure of <code class="language-plaintext highlighter-rouge">compute_results()</code> and ignore all passes. For that you could use the <code class="language-plaintext highlighter-rouge">_</code> case. <code class="language-plaintext highlighter-rouge">_</code> in the case of a <code class="language-plaintext highlighter-rouge">match</code> statement or expression means “everything else”. So, to write our <code class="language-plaintext highlighter-rouge">FunctionStatus</code> handling functionality in a way when only failures are handled, we could do the following:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">compute_results</span><span class="p">();</span>
-    <span class="k">match</span> <span class="n">res</span> <span class="p">{</span>
-      <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">FAILURE</span><span class="p">(</span><span class="n">severity</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="k">match</span> <span class="n">severity</span> <span class="p">{</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">FATAL</span><span class="p">(</span><span class="n">message</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"FATAL: {}"</span><span class="p">,</span> <span class="n">message</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">BENIGN</span><span class="p">(</span><span class="n">message</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"BENIGN: {}"</span><span class="p">,</span> <span class="n">message</span><span class="p">);</span>
-          <span class="p">}</span>
-        <span class="p">};</span>
-      <span class="p">}</span>
-      <span class="mi">_</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="c">// Here goes the handling of "everything else", or it can be left out completely</span>
-      <span class="p">}</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>The same thing can be applied to <code class="language-plaintext highlighter-rouge">SeverityStatus</code>. If you want to ignore benign failures, you can replace that specific case with <code class="language-plaintext highlighter-rouge">_</code>.</p>
-
-<p>The only drawback to using <code class="language-plaintext highlighter-rouge">_</code> is that “everything else” will include any options you include in future instances, so I’d personally strongly advocate against the use of <code class="language-plaintext highlighter-rouge">_</code>. If you want to leave some cases unhandled, you could still include them and let them point to an empty block of code, e.g.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="nf">compute_results</span><span class="p">();</span>
-    <span class="k">match</span> <span class="n">res</span> <span class="p">{</span>
-      <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">FAILURE</span><span class="p">(</span><span class="n">severity</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="k">match</span> <span class="n">severity</span> <span class="p">{</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">FATAL</span><span class="p">(</span><span class="n">message</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"FATAL: {}"</span><span class="p">,</span> <span class="n">message</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">SeverityStatus</span><span class="p">::</span><span class="nf">BENIGN</span><span class="p">(</span><span class="mi">_</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="c">// Leaving this case unhandled</span>
-            <span class="c">// NOTE: you can't print _. If you change your mind and decide to</span>
-            <span class="c">// actually handle this case, replace `_` with a valid variable name.</span>
-          <span class="p">}</span>
-        <span class="p">};</span>
-      <span class="p">}</span>
-      <span class="nn">FunctionStatus</span><span class="p">::</span><span class="nf">PASS</span><span class="p">(</span><span class="mi">_</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="c">// Leaving this case unhandled</span>
-      <span class="p">}</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>One last thing I wanted to touch on before I wrap up with this post. When using <code class="language-plaintext highlighter-rouge">match</code> to unstructure objects, you’ll come across projects with multiple fields, or even worse, nested object structures. Our <code class="language-plaintext highlighter-rouge">Person</code> structure can be used as an example here. How would we match this object? following’s how.</p>
-
-<p>Say you’re interested in only unstructuring the gender and the age of a person object. You’d do this as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">fn</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>
-    <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-      <span class="n">name</span><span class="p">:</span> <span class="s">"Fadi Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">(),</span>
-      <span class="n">age</span><span class="p">:</span> <span class="mi">27</span><span class="p">,</span>
-      <span class="n">gender</span><span class="p">:</span> <span class="nn">PersonGender</span><span class="p">::</span><span class="n">MALE</span><span class="p">,</span>
-    <span class="p">};</span>
-
-    <span class="k">match</span> <span class="n">person</span> <span class="p">{</span>
-      <span class="n">Person</span> <span class="p">{</span> <span class="n">age</span><span class="p">,</span> <span class="n">gender</span><span class="p">,</span> <span class="o">..</span> <span class="p">}</span> <span class="k">=&gt;</span> <span class="p">{</span>
-        <span class="nd">println!</span><span class="p">(</span><span class="s">"age: {}"</span><span class="p">,</span> <span class="n">age</span><span class="p">);</span>
-        <span class="k">match</span> <span class="n">gender</span> <span class="p">{</span>
-          <span class="nn">PersonGender</span><span class="p">::</span><span class="n">MALE</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"gender is male"</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">PersonGender</span><span class="p">::</span><span class="n">FEMALE</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"gender is female"</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">PersonGender</span><span class="p">::</span><span class="n">UNDISCLOSED</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"gender Undisclosed"</span><span class="p">);</span>
-          <span class="p">}</span>
-          <span class="nn">PersonGender</span><span class="p">::</span><span class="nf">OTHER</span><span class="p">(</span><span class="n">g</span><span class="p">)</span> <span class="k">=&gt;</span> <span class="p">{</span>
-            <span class="nd">println!</span><span class="p">(</span><span class="s">"gender: {}"</span><span class="p">,</span> <span class="n">g</span><span class="p">);</span>
-          <span class="p">}</span>
-        <span class="p">};</span>
-      <span class="p">}</span>
-    <span class="p">}</span>
-  <span class="p">}</span>
-</code></pre></div></div>
-
-<p>That’s all I have for now. Don’t hesitate to hit me up if you have questions.</p>Fadi Hanna Al-KassYou’ve probably worked with enums before, but if you haven’t, they’re basically a way to have a selection out of a number of different options. A Person struct could contain a gender field that points to an enum of three options (Male, Female, and Undisclosed), i.e.:My Thoughts on TypeScript2017-04-14T05:00:00+00:002017-04-14T05:00:00+00:00/My%20Thoughts%20on%20TypeScript<p>I was introduced to TypeScript when it first came with angular 2. However, I tried to avoid it as much as possible. This was actually the main reason of why I left angular in favor of Vue. “A new quirky front-end language is the last thing I would need,” I thought.</p>
-
-<p>That was true until I was deep into my <a href="https://github.com/finnlp/">NLP</a> project in late 2016. The code base was relatively large, so many modules and functions. A friend of mine, recommended TypeScript, and I tried it. I’ve been working with it for the last 4 months, and here are my thoughts.</p>
-
-<h2 id="type-checking-is-more-important-than-what-you-think">Type checking is more important than what you think</h2>
-
-<p>You might ask: why would anyone spend their time and energy writing:</p>
-
-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">add</span> <span class="p">(</span><span class="nx">a</span><span class="p">:</span> <span class="nx">number</span><span class="p">,</span> <span class="nx">b</span><span class="p">:</span> <span class="nx">number</span><span class="p">):</span> <span class="nx">number</span> <span class="p">{</span>
-	<span class="k">return</span> <span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span><span class="p">;</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>Instead of:</p>
-
-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">add</span> <span class="p">(</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">)</span> <span class="p">{</span>
-	<span class="k">return</span> <span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span><span class="p">;</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>The TL:DR; answer is:</p>
-
-<ul>
-  <li>Reduced bugs.</li>
-  <li>Compile time errors instead of runtime errors.</li>
-  <li>Better tooling.</li>
-  <li>Code completion.</li>
-</ul>
-
-<p>As for time and energy, developers usually spend more time reading code than writing it. TypeScript is clean and well-designed (a Microsoft product by Anders Hejlsberg the author of C#, Turbo Pascal and Delphi). So while you’re going to spend a little bit extra time writing code, but with better tooling you’ll be reading less. Especially when working in a team.</p>
-
-<p>As you import the module, you’ll have inline documentation, code completion and you can jump to definition. Those are limited, or sometimes, not even possible with a dynamic language such as JavaScript.</p>
-
-<h3 id="reduced-bugs-and-compile-time-errors">Reduced bugs and compile time errors</h3>
+int handleSub(const Request* req, Response* res) {
+  printf("res->data = %d - %d\n", req->params[0], req->params[1]);
+  res->data = req->params[0] - req->params[1];
+  return true;
+}
+
+int handleMul(const Request* req, Response* res) {
+  printf("res->data = %d * %d\n", req->params[0], req->params[1]);
+  res->data = req->params[0] * req->params[1];
+  return true;
+}
+
+int handleDiv(const Request* req, Response* res) {
+  printf("res->data = %d / %d\n", req->params[0], req->params[1]);
+  res->data = req->params[0] / req->params[1];
+  return true;
+}
+
+int handleRequest(const Request* req, Response* res) {
+  switch (req->op) {
+    case ADD:
+      return handleAdd(req, res);
+    case SUB:
+      return handleSub(req, res);
+    case MUL:
+      return handleMul(req, res);
+    case DIV:
+      return handleDiv(req, res);
+    default:
+      return false;
+  }
+}
+
+ +

And can be called as follows:

+ +
if (handleRequest(&req, &res)) {
+  res.status = true;
+}
+else {
+  res.status = false;
+}
+
+ +

The response can be sent to the client as follows:

+ +
write(comm_fd, (byte*)&res, sizeof(Response));
+
+ +

And there we have a fully functional RPC server implementation capable of performing just about anything when expanded.

+ +
+

The demo I referred to at the beginning of this post can be found here

+
]]>
Fadi Hanna Al-Kass
Crafting Code - Building Common Interfaces2017-06-20T05:00:00+00:002017-06-20T05:00:00+00:00/Crafting%20Code%201When writing libraries, APIs, and SDKs, the less stuff you ask your user to memorize the better it looks to you and feels to them. For instance, if you were to write a Math library that performs some arithmetic operations, you could write your library functions as so:

+ +
fn add(op1: f32, op2: f32) -> f32 {
+  op1 + op2
+}
+
+fn sub(op1: f32, op2: f32) -> f32 {
+  op1 - op2
+}
+
+fn mul(op1: f32, op2: f32) -> f32 {
+  op1 * op2
+}
+
+fn div(op1: f32, op2: f32) -> f32 {
+  op1 / op2
+}
+
+ +

And that’ll require the user to import his/her desired function or set of functions as needed. This is fine, but wouldn’t it be better if you could provide only one function that does all these operations? We’re going to call this function a common interface, but this procedure is called a passthrough in the professional field. A passthrough function is a multi-purpose entry point to a set of different classes or functions. In the case of our Math library, we could have our passthrough function written as follows:

+ +
fn passthrough(operation: &'static str, op1: f32, op2: f32) -> f32 {
+  return match operation {
+    "+" => add(op1, op2),
+    "-" => sub(op1, op2),
+    "*" => mul(op1, op2),
+    "/" => div(op1, op2),
+    _ => 0 as f32, //Return 0 if unknown operation. Near future bug alert!!!
+  };
+}
+
+ +

That allows us to do something like this:

+ +
let res = passthrough("+", 10 as f32, 12.3);
+
+ +

Instead of this:

+ +
let res = add(32.4, 12 as f32);
+
+ +

But there’s more we could do here. So, for instance, instead of specifying the operation as a string and expose our code to all sorts of correctness bugs (afterall, our passthrough() function won’t warn us about an invalid operation), we could do something like this:

+ +
enum OperationType {
+    ADD,
+    SUB,
+    MUL,
+    DIV,
+}
+
+fn passthrough(operation: OperationType, op1: f32, op2: f32) -> f32 {
+  return match operation {
+    OperationType::ADD => add(op1, op2),
+    OperationType::SUB => sub(op1, op2),
+    OperationType::MUL => mul(op1, op2),
+    OperationType::DIV => div(op1, op2),
+  };
+}
+
+ +

That will at least force the user to select one of many options, and anything that’s not on the list won’t slide. But that’s not all either. There’s still more that can be done to tweak our code.

+ +

Notice how passthrough will always take two operands, no more or less parameters. What if, in the future, you decide to add an operation that requires only one operand (a square root function for example). You may be able to get away with something as easy as passthrough(OperationType::SQRT, 25, 0), but that neither looks clean nor is something a team of professional developers would approve of. Perhaps we could turn our operands into a flexible object, and for the sake of simplicity we shall call our object Request and have it implemented as follows:

+ +
enum Request {
+    NoOps,
+    OneOp(f32),
+    TwoOps(f32, f32),
+    ThreeOps(f32, f32, f32),
+}
+
+ +

And re-implement our passthrough() function to work with a Request object as follows:

+ +
fn passthrough(operation: OperationType, req: Request) -> f32 {
+  return match operation {
+    OperationType::ADD => add(req),
+    OperationType::SUB => sub(req),
+    OperationType::MUL => mul(req),
+    OperationType::DIV => div(req),
+  };
+}
+
+ +

And re-implement our arithmetic functions to use our Request object instead of straight operands:

+ +
fn add(req: Request) -> f32 {
+  return match req {
+    Request::NoOps => 0 as f32,
+    Request::OneOp(a) => a,w
+    Request::TwoOps(a, b) => a + b,
+    Request::ThreeOps(a, b, c) => a + b + c,
+  };
+}
+
+ +

And the resulting code will then allow us to do something like this:

+ +
let res = passthrough(OperationType::ADD, Request::NoOps);
+
+ +

Or this:

+ +
let res = passthrough(OperationType::ADD, Request::TwoOps(10.1, 40.5));
+
+ +

Or this:

+ +
let res = passthrough(OperationType::ADD, Request::ThreeOps(10.1, 40.5));
+
+ +

There’s still more room for improvement, but you get the point.

+ +

So, “why should I consider a passthrough design?”, you may wonder! Here are some reasons why:

+ +
    +
  • +

    Passthroughs allow you to completely maintain your own code when working with a team of developers. That is to say your code needs not be scattered around, nor will anyone need direct access to any of your functions; you make your inner functions private, provide a passthrough function and there you roll ^_^.

    +
  • +
  • +

    Documentation becomes a breeze. Think about it. Instead of having to document every single function and provide snippets and use cases, you can keep all these functions private and only worry about documenting one: your passthrough() function. This can save you lots and lots of time.

    +
  • +
]]>
Fadi Hanna Al-Kass
Enum and Match Systems in Rust2017-06-17T05:00:00+00:002017-06-17T05:00:00+00:00/Enum%20and%20Match%20Systems%20in%20RustYou’ve probably worked with enums before, but if you haven’t, they’re basically a way to have a selection out of a number of different options. A Person struct could contain a gender field that points to an enum of three options (Male, Female, and Undisclosed), i.e.:

+ +
  enum PersonGender {
+    MALE,
+    FEMALE,
+    UNDISCLOSED,
+  }
+
+  struct Person {
+    name: String,
+    age: i8,
+    gender: PersonGender,
+  }
+
+  fn main() {
+    let person = Person {
+      name: "Fadi Hanna Al-Kass".to_string(),
+      age: 27,
+      gender: PersonGender::MALE,
+    };
+  }
+
+ +

Now, what if a person so chooses to identify as something else? In that case, you could add a 4th option (Other) and attach a value of type String to it. Here’s what your end result would look like:

+ +
  enum PersonGender {
+    MALE,
+    FEMALE,
+    UNDISCLOSED,
+    OTHER(String),
+  }
+
+  struct Person {
+    name: String,
+    age: i8,
+    gender: PersonGender,
+  }
+
+  fn main() {
+    let person = Person {
+      name: "Jake Smith".to_string(),
+      age: 27,
+      gender: PersonGender::OTHER("Agender".to_string()),
+    };
+  }
+
+ +

Of course enums don’t have to be part of a struct, and enum values don’t have to be primitives either. An enum value can point to a struct or even another enum and so on. For instance, you can write a function that returns a status that’s either PASS or FAILURE. PASS can include a string while FAILURE can contain more information about the severity of the failure. This functionality can be achieved as so:

+ +
  enum SeverityStatus {
+    BENIGN(String),
+    FATAL(String),
+  }
+
+  enum FunctionStatus {
+    PASS(String),
+    FAILURE(SeverityStatus),
+  }
+
+  fn compute_results() -> FunctionStatus {
+    // Successful execution would look like the following:
+    // return FunctionStatus::PASS("Everything looks good".to_string());
+
+    // While a failure would be indicated as follows:
+    return FunctionStatus::FAILURE(SeverityStatus::FATAL("Continuing beyond this point will cause more damage to the hardware".to_string()));
+  }
+
+ +

Now onto match. One of the things I love the most about match is its ability to unstructure objects. Let’s take a second look at our last code snippet and see how we can possibly handle the response coming back to us from compute_results(). For this, I’d definitely use a set of match statements, e.g.:

+ +
  fn main() {
+    let res = compute_results();
+    match res {
+      FunctionStatus::PASS(x) => {
+        // Handling a PASS response
+        println!("PASS: {}", x);
+      }
+      FunctionStatus::FAILURE(x) => {
+        // Handling a FAILURE response
+        match x {
+          SeverityStatus::BENIGN(y) => {
+            // Handling a BENIGN FAILURE response
+            println!("BENIGN: {}", y);
+          }
+          SeverityStatus::FATAL(y) => {
+            // Handling a FATAL FAILURE response
+            println!("FATAL: {}", y);
+          }
+        };
+      }
+    };
+  }
+
+ +

Now, if you happen to add more options to any of the two enums (say, a WARN option to FunctionStatus or UNCATEGORIZED to SeverityStatus), the compiler will refuse to compile your code until all possible cases are handled. This is definitely a plus as it forces you to think about all the paths your code could take.

+ +

However, there will be times when you really only want to handle specific cases and not the rest. For instance, we may only be interested in handling the case of failure of compute_results() and ignore all passes. For that you could use the _ case. _ in the case of a match statement or expression means “everything else”. So, to write our FunctionStatus handling functionality in a way when only failures are handled, we could do the following:

+ +
  fn main() {
+    let res = compute_results();
+    match res {
+      FunctionStatus::FAILURE(severity) => {
+        match severity {
+          SeverityStatus::FATAL(message) => {
+            println!("FATAL: {}", message);
+          }
+          SeverityStatus::BENIGN(message) => {
+            println!("BENIGN: {}", message);
+          }
+        };
+      }
+      _ => {
+        // Here goes the handling of "everything else", or it can be left out completely
+      }
+    };
+  }
+
+ +

The same thing can be applied to SeverityStatus. If you want to ignore benign failures, you can replace that specific case with _.

+ +

The only drawback to using _ is that “everything else” will include any options you include in future instances, so I’d personally strongly advocate against the use of _. If you want to leave some cases unhandled, you could still include them and let them point to an empty block of code, e.g.:

+ +
  fn main() {
+    let res = compute_results();
+    match res {
+      FunctionStatus::FAILURE(severity) => {
+        match severity {
+          SeverityStatus::FATAL(message) => {
+            println!("FATAL: {}", message);
+          }
+          SeverityStatus::BENIGN(_) => {
+            // Leaving this case unhandled
+            // NOTE: you can't print _. If you change your mind and decide to
+            // actually handle this case, replace `_` with a valid variable name.
+          }
+        };
+      }
+      FunctionStatus::PASS(_) => {
+        // Leaving this case unhandled
+      }
+    };
+  }
+
+ +

One last thing I wanted to touch on before I wrap up with this post. When using match to unstructure objects, you’ll come across projects with multiple fields, or even worse, nested object structures. Our Person structure can be used as an example here. How would we match this object? following’s how.

+ +

Say you’re interested in only unstructuring the gender and the age of a person object. You’d do this as follows:

+ +
  fn main() {
+    let person = Person {
+      name: "Fadi Hanna Al-Kass".to_string(),
+      age: 27,
+      gender: PersonGender::MALE,
+    };
+
+    match person {
+      Person { age, gender, .. } => {
+        println!("age: {}", age);
+        match gender {
+          PersonGender::MALE => {
+            println!("gender is male");
+          }
+          PersonGender::FEMALE => {
+            println!("gender is female");
+          }
+          PersonGender::UNDISCLOSED => {
+            println!("gender Undisclosed");
+          }
+          PersonGender::OTHER(g) => {
+            println!("gender: {}", g);
+          }
+        };
+      }
+    }
+  }
+
+ +

That’s all I have for now. Don’t hesitate to hit me up if you have questions.

]]>
Fadi Hanna Al-Kass
My Thoughts on TypeScript2017-04-14T05:00:00+00:002017-04-14T05:00:00+00:00/My%20Thoughts%20on%20TypeScriptI was introduced to TypeScript when it first came with angular 2. However, I tried to avoid it as much as possible. This was actually the main reason of why I left angular in favor of Vue. “A new quirky front-end language is the last thing I would need,” I thought.

+ +

That was true until I was deep into my NLP project in late 2016. The code base was relatively large, so many modules and functions. A friend of mine, recommended TypeScript, and I tried it. I’ve been working with it for the last 4 months, and here are my thoughts.

+ +

Type checking is more important than what you think

+ +

You might ask: why would anyone spend their time and energy writing:

+ +
function add (a: number, b: number): number {
+	return a + b;
+}
+
+ +

Instead of:

+ +
function add (a, b) {
+	return a + b;
+}
+
+ +

The TL:DR; answer is:

+ +
    +
  • Reduced bugs.
  • +
  • Compile time errors instead of runtime errors.
  • +
  • Better tooling.
  • +
  • Code completion.
  • +
+ +

As for time and energy, developers usually spend more time reading code than writing it. TypeScript is clean and well-designed (a Microsoft product by Anders Hejlsberg the author of C#, Turbo Pascal and Delphi). So while you’re going to spend a little bit extra time writing code, but with better tooling you’ll be reading less. Especially when working in a team.

+ +

As you import the module, you’ll have inline documentation, code completion and you can jump to definition. Those are limited, or sometimes, not even possible with a dynamic language such as JavaScript.

+ +

Reduced bugs and compile time errors

-<p>Take the previous example for instance:</p> +

Take the previous example for instance:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> -<span class="kd">let</span> <span class="nx">b</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">string</span><span class="dl">"</span><span class="p">;</span> -<span class="nx">add</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">);</span> -</code></pre></div></div> +
let a = 1;
+let b = "string";
+add(a, b);
+
-<p>In javascript, the aforementioned code will act like nothing is wrong and would just return <code class="language-plaintext highlighter-rouge">"1string"</code>, i.e. It will fail silently, not even a runtime error will be produced. Which is the last thing you would want.</p> +

In javascript, the aforementioned code will act like nothing is wrong and would just return "1string", i.e. It will fail silently, not even a runtime error will be produced. Which is the last thing you would want.

-<p>A wise man once said:</p> +

A wise man once said:

-<blockquote> - <p>Well engineered solutions fails early, fails fast, fails often.</p> -</blockquote> +
+

Well engineered solutions fails early, fails fast, fails often.

+
-<p>And I can’t emphasize enough how true this statement is.</p> +

And I can’t emphasize enough how true this statement is.

-<p>You might argue that “no one would pass a string to a function called <code class="language-plaintext highlighter-rouge">add</code>, that’s too obvious”. I agree, however, think of a larger code base, many functions, classes, abstractions, on multiple modules. Things can get out of hands in JavaScript pretty quickly.</p> +

You might argue that “no one would pass a string to a function called add, that’s too obvious”. I agree, however, think of a larger code base, many functions, classes, abstractions, on multiple modules. Things can get out of hands in JavaScript pretty quickly.

-<p>Have a look at this code for instance:</p> +

Have a look at this code for instance:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="kd">function</span> <span class="nx">getAuthorLines</span><span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="p">{</span> - <span class="k">return</span> <span class="nx">text</span><span class="p">.</span><span class="nx">match</span><span class="p">(</span><span class="sr">/^author: </span><span class="se">(</span><span class="sr">.*</span><span class="se">)</span><span class="sr">$/gmi</span><span class="p">);</span> -<span class="p">}</span> +

+function getAuthorLines(text) {
+	return text.match(/^author: (.*)$/gmi);
+}
 
-<span class="kd">function</span> <span class="nx">getAuthorNames</span><span class="p">(</span><span class="nx">lines</span><span class="p">)</span> <span class="p">{</span>
-	<span class="k">return</span> <span class="nx">lines</span><span class="p">.</span><span class="nx">map</span><span class="p">((</span><span class="nx">line</span><span class="p">)</span><span class="o">=&gt;</span><span class="nx">line</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="mi">8</span><span class="p">))</span>
-<span class="p">}</span>
+function getAuthorNames(lines) {
+	return lines.map((line)=>line.substr(8))
+}
 
-<span class="kd">let</span> <span class="nx">text</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Paper title: TypeScript for the Win</span><span class="se">\n</span><span class="s2">Author: Alex Corvi</span><span class="se">\n</span><span class="s2">Author: John Doe</span><span class="se">\n</span><span class="s2">Author: Jane Doe</span><span class="se">\n</span><span class="dl">"</span><span class="p">;</span>
+let text = "Paper title: TypeScript for the Win\nAuthor: Alex Corvi\nAuthor: John Doe\nAuthor: Jane Doe\n";
 
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getAuthorNames</span><span class="p">(</span><span class="nx">getAuthorLines</span><span class="p">(</span><span class="nx">text</span><span class="p">)));</span>
+console.log(getAuthorNames(getAuthorLines(text)));
 
-</code></pre></div></div>
+
-<p>What do you expect the result to be? You guessed it, it’s:</p> +

What do you expect the result to be? You guessed it, it’s:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span> - <span class="dl">"</span><span class="s2">Alex Corvi</span><span class="dl">"</span><span class="p">,</span> - <span class="dl">"</span><span class="s2">John Doe</span><span class="dl">"</span><span class="p">,</span> - <span class="dl">"</span><span class="s2">Jane Doe</span><span class="dl">"</span><span class="p">,</span> -<span class="p">]</span> -</code></pre></div></div> +
[
+	"Alex Corvi",
+	"John Doe",
+	"Jane Doe",
+]
+
-<p>Now add the following line:</p> +

Now add the following line:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getAuthorNames</span><span class="p">(</span><span class="nx">getAuthorLines</span><span class="p">(</span><span class="nx">text</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">30</span><span class="p">))));</span> -</code></pre></div></div> +
console.log(getAuthorNames(getAuthorLines(text.substr(0,30))));
+
-<p>Ouch! That’s a runtime error! That’s because <code class="language-plaintext highlighter-rouge">String.match</code> doesn’t always return an array, it might return <code class="language-plaintext highlighter-rouge">null</code>.</p> +

Ouch! That’s a runtime error! That’s because String.match doesn’t always return an array, it might return null.

-<p>Here’s another code, can you spot what’s wrong?</p> +

Here’s another code, can you spot what’s wrong?

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">theThing</span> <span class="o">=</span> <span class="kc">null</span><span class="p">;</span> -<span class="kd">var</span> <span class="nx">replaceThing</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> - <span class="kd">var</span> <span class="nx">priorThing</span> <span class="o">=</span> <span class="nx">theThing</span><span class="p">;</span> - <span class="kd">var</span> <span class="nx">unused</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> - <span class="k">if</span> <span class="p">(</span><span class="nx">priorThing</span><span class="p">)</span> <span class="p">{</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">hi</span><span class="dl">"</span><span class="p">);</span> - <span class="p">}</span> - <span class="p">};</span> - <span class="nx">theThing</span> <span class="o">=</span> <span class="p">{</span> - <span class="na">longStr</span><span class="p">:</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">(</span><span class="mi">1000000</span><span class="p">).</span><span class="nx">join</span><span class="p">(</span><span class="dl">'</span><span class="s1">*</span><span class="dl">'</span><span class="p">),</span> - <span class="na">someMethod</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">abc</span><span class="dl">"</span><span class="p">);</span> - <span class="p">}</span> - <span class="p">};</span> -<span class="p">};</span> -<span class="nx">setInterval</span><span class="p">(</span><span class="nx">replaceThing</span><span class="p">,</span> <span class="mi">1000</span><span class="p">);</span> -</code></pre></div></div> +
var theThing = null;
+var replaceThing = function () {
+	var priorThing = theThing;
+	var unused = function () {
+		if (priorThing) {
+			console.log("hi");
+		}
+	};
+	theThing = {
+		longStr: new Array(1000000).join('*'),
+		someMethod: function () {
+			console.log("abc");
+		}
+	};
+};
+setInterval(replaceThing, 1000);
+
-<p>That was a classic example of how you can cause memory leaks in JavaScript. This one leaks 1 MegaByte per second. In TypeScript, You can’t reassign the <code class="language-plaintext highlighter-rouge">theThing</code> variable from <code class="language-plaintext highlighter-rouge">null</code> to <code class="language-plaintext highlighter-rouge">Object</code>.</p> +

That was a classic example of how you can cause memory leaks in JavaScript. This one leaks 1 MegaByte per second. In TypeScript, You can’t reassign the theThing variable from null to Object.

-<p>That doesn’t mean your applications will be bug-free. That’s never true, for any language. But surely, using TypeScript you can avoid a whole class of bugs.</p> +

That doesn’t mean your applications will be bug-free. That’s never true, for any language. But surely, using TypeScript you can avoid a whole class of bugs.

-<p>One might argue, that being an experienced developer will help to avoid such bugs. Again, I agree, but:</p> +

One might argue, that being an experienced developer will help to avoid such bugs. Again, I agree, but:

-<ul> - <li>TypeScript (or static typing in general) is like a seat belt, not matter how good driver you are, you should always wear one.</li> - <li>The JavaScript community, is heavily reliant on modules (node modules) and those have a huge variance in quality.</li> -</ul> +
    +
  • TypeScript (or static typing in general) is like a seat belt, not matter how good driver you are, you should always wear one.
  • +
  • The JavaScript community, is heavily reliant on modules (node modules) and those have a huge variance in quality.
  • +
-<blockquote> - <p>Static typing is like a seat belt, no matter how good driver you are, you should always wear one.</p> -</blockquote> +
+

Static typing is like a seat belt, no matter how good driver you are, you should always wear one.

+
-<h3 id="better-tooling-and-code-completion">Better tooling and code completion</h3> +

Better tooling and code completion

-<p>Code analysis, like abstract syntax trees, helps a lot with tooling. Code analysis is what makes code completion, linting, debugging tools, tree shaking tools possible. However, the dynamic nature of JavaScript makes it really hard for such tools to truly understand your code.</p> +

Code analysis, like abstract syntax trees, helps a lot with tooling. Code analysis is what makes code completion, linting, debugging tools, tree shaking tools possible. However, the dynamic nature of JavaScript makes it really hard for such tools to truly understand your code.

-<p>Take for example <a href="https://github.com/rollup/rollup">rollup</a>, a bundling tool, have been recently integrated into Vue.js and React, that is supposed to tree-shake your bundles making them lighter by removing inaccessible and dead code. The author of which, Rich Harris, <a href="https://github.com/rollup/rollup/wiki/Troubleshooting#tree-shaking-doesnt-seem-to-be-working">mentions</a>:</p> +

Take for example rollup, a bundling tool, have been recently integrated into Vue.js and React, that is supposed to tree-shake your bundles making them lighter by removing inaccessible and dead code. The author of which, Rich Harris, mentions:

-<blockquote> - <p>Because static analysis in a dynamic language like JavaScript is hard, there will occasionally be false positives […] Rollup’s static analysis will improve over time, but it will never be perfect in all cases – that’s just JavaScript.</p> -</blockquote> +
+

Because static analysis in a dynamic language like JavaScript is hard, there will occasionally be false positives […] Rollup’s static analysis will improve over time, but it will never be perfect in all cases – that’s just JavaScript.

+
-<p>So there’s really a limit to what can be achieved in JavaScript tooling.</p> +

So there’s really a limit to what can be achieved in JavaScript tooling.

-<p>One of TypeScript’s goals was to remove such limits, and they sure did.</p> +

One of TypeScript’s goals was to remove such limits, and they sure did.

-<p>Here are my favorites:</p> +

Here are my favorites:

-<ul> - <li>Great code completion, with <strong>Intellisense</strong>.</li> - <li>Goto symbol and show all symbols.</li> - <li>Better code reformatting.</li> - <li>A bunch of features that are provided with TSLint but not in ESLint.</li> - <li><a href="https://johnpapa.net/refactoring-with-visual-studio-code/">Easy refactoring (e.g. renaming a symbol).</a></li> -</ul> +
    +
  • Great code completion, with Intellisense.
  • +
  • Goto symbol and show all symbols.
  • +
  • Better code reformatting.
  • +
  • A bunch of features that are provided with TSLint but not in ESLint.
  • +
  • Easy refactoring (e.g. renaming a symbol).
  • +
-<blockquote> - <p><strong>IntelliSense</strong> is the general term for a number of features: List Members, Parameter Info, Quick Info, and Complete Word. These features help you to learn more about the code you are using, keep track of the parameters you are typing, and add calls to properties and methods with only a few keystrokes. -Microsoft Developer Network</p> -</blockquote> +
+

IntelliSense is the general term for a number of features: List Members, Parameter Info, Quick Info, and Complete Word. These features help you to learn more about the code you are using, keep track of the parameters you are typing, and add calls to properties and methods with only a few keystrokes. +Microsoft Developer Network

+
-<h2 id="the-syntax">The Syntax</h2> +

The Syntax

-<h3 id="but-i-like-es6">But I like ES6…</h3> +

But I like ES6…

-<p>I hope I’ve convinced you enough to try out TypeScript. The syntax shouldn’t be alien to a JavaScript programmer. Especially those who have tried ES6/ES7.</p> +

I hope I’ve convinced you enough to try out TypeScript. The syntax shouldn’t be alien to a JavaScript programmer. Especially those who have tried ES6/ES7.

-<p>TypeScript brands itself as a <em>“JavaScript Superset”</em>, so all valid JavaScript (ES3, ES5, ES6, ES7 …etc) is valid TypeScript. Everything you’ve been accustomed to, from flow controls to assignments.</p> +

TypeScript brands itself as a “JavaScript Superset”, so all valid JavaScript (ES3, ES5, ES6, ES7 …etc) is valid TypeScript. Everything you’ve been accustomed to, from flow controls to assignments.

-<p>So instead of having a totally new syntax (like PureScript, Elm and Dart), TypeScript builds on top of JavaScript syntax. Yet, it adds it’s own flavor on top.</p> +

So instead of having a totally new syntax (like PureScript, Elm and Dart), TypeScript builds on top of JavaScript syntax. Yet, it adds it’s own flavor on top.

-<h3 id="enough-talk-show-me-the-code">Enough talk, show me the code</h3> +

Enough talk, show me the code

-<p>I can easily bet that all javascript developers will be able to understand the following piece of code:</p> +

I can easily bet that all javascript developers will be able to understand the following piece of code:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="kd">let</span> <span class="nx">x</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> -<span class="kd">let</span> <span class="nx">y</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">500</span><span class="p">;</span> +

+let x: number = 1;
+let y: number = 500;
 
-<span class="kd">function</span> <span class="nx">getRand</span> <span class="p">(</span><span class="nx">min</span><span class="p">:</span> <span class="nx">number</span><span class="p">,</span> <span class="nx">max</span><span class="p">:</span> <span class="nx">number</span><span class="p">):</span> <span class="nx">number</span> <span class="p">{</span>
-	<span class="k">return</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">floor</span><span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">*</span> <span class="p">(</span><span class="nx">max</span> <span class="o">-</span> <span class="nx">min</span><span class="p">))</span> <span class="o">+</span> <span class="nx">min</span><span class="p">;</span>
-<span class="p">}</span>
+function getRand (min: number, max: number): number {
+	return Math.floor(Math.random() * (max - min)) + min;
+}
 
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getRand</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">));</span>
+console.log(getRand(x, y));
 
-</code></pre></div></div>
+
-<p>So is this:</p> +

So is this:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="kd">class</span> <span class="nx">House</span> <span class="p">{</span> - <span class="nl">address</span><span class="p">:</span> <span class="nx">string</span><span class="p">;</span> - <span class="nl">bedrooms</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> - <span class="nl">area</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> - <span class="nl">safeNeighborhood</span><span class="p">:</span><span class="nx">boolean</span><span class="p">;</span> - <span class="nl">goodCondition</span><span class="p">:</span><span class="nx">boolean</span><span class="p">;</span> - <span class="kr">private</span> <span class="nx">priceCoefficient</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">65</span><span class="p">;</span> - <span class="kd">get</span> <span class="nx">price</span><span class="p">():</span> <span class="nx">number</span> <span class="p">{</span> - <span class="k">return</span> <span class="p">((</span><span class="k">this</span><span class="p">.</span><span class="nx">bedrooms</span> <span class="o">*</span> <span class="k">this</span><span class="p">.</span><span class="nx">area</span><span class="p">)</span> <span class="o">+</span> - <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">safeNeighborhood</span> <span class="p">?</span> <span class="mi">1000</span> <span class="p">:</span> <span class="mi">0</span> <span class="p">)</span> <span class="o">+</span> - <span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">goodCondition</span> <span class="p">?</span> <span class="mi">1000</span> <span class="p">:</span> <span class="mi">0</span> <span class="p">))</span> <span class="o">*</span> <span class="k">this</span><span class="p">.</span><span class="nx">priceCoefficient</span><span class="p">;</span> - <span class="p">}</span> -<span class="p">}</span> +

+class House {
+	address: string;
+	bedrooms: number;
+	area: number;
+	safeNeighborhood:boolean;
+	goodCondition:boolean;
+	private priceCoefficient: number = 65;
+	get price(): number {
+		return ((this.bedrooms * this.area) +
+			(this.safeNeighborhood ? 1000 : 0 ) +
+			(this.goodCondition ? 1000 : 0 )) * this.priceCoefficient;
+	}
+}
 
-<span class="kd">let</span> <span class="nx">myHouse</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">House</span><span class="p">();</span>
-<span class="nx">myHouse</span><span class="p">.</span><span class="nx">bedrooms</span> <span class="o">=</span> <span class="mi">4</span><span class="p">;</span>
-<span class="nx">myHouse</span><span class="p">.</span><span class="nx">area</span> <span class="o">=</span> <span class="mi">300</span><span class="p">;</span>
-<span class="nx">myHouse</span><span class="p">.</span><span class="nx">safeNeighborhood</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
-<span class="nx">myHouse</span><span class="p">.</span><span class="nx">goodCondition</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
+let myHouse = new House();
+myHouse.bedrooms = 4;
+myHouse.area = 300;
+myHouse.safeNeighborhood = true;
+myHouse.goodCondition = true;
 
-<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">myHouse</span><span class="p">.</span><span class="nx">price</span><span class="p">)</span>
+console.log(myHouse.price)
 
-</code></pre></div></div>
+
-<p>That was a major portion of what you’ll find in a TypeScript project.</p> +

That was a major portion of what you’ll find in a TypeScript project.

-<h3 id="interfaces">Interfaces</h3> +

Interfaces

-<p>Interfaces, simply put, is a way to declare JSON object types.</p> +

Interfaces, simply put, is a way to declare JSON object types.

-<p>You can write your object type definition like this:</p> +

You can write your object type definition like this:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">myObj</span><span class="p">:</span> <span class="p">{</span> <span class="nl">a</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> <span class="nl">str</span><span class="p">:</span> <span class="nx">string</span><span class="p">;</span> <span class="p">}</span> <span class="o">=</span> <span class="p">{</span> - <span class="na">a</span><span class="p">:</span> <span class="mi">123</span><span class="p">,</span> - <span class="na">str</span><span class="p">:</span> <span class="dl">"</span><span class="s2">my string</span><span class="dl">"</span> -<span class="p">}</span> -</code></pre></div></div> +
let myObj: { a: number; str: string; } = {
+	a: 123,
+	str: "my string"
+}
+
-<p>Or you can declare a re-usable interface:</p> +

Or you can declare a re-usable interface:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">interface</span> <span class="nx">MyObj</span> <span class="p">{</span> - <span class="nl">a</span><span class="p">:</span> <span class="nx">number</span><span class="p">;</span> - <span class="nl">str</span><span class="p">:</span> <span class="nx">string</span><span class="p">;</span> -<span class="p">}</span> +
interface MyObj {
+	a: number;
+	str: string;
+}
 
-<span class="kd">let</span> <span class="nx">myObj1</span><span class="p">:</span> <span class="nx">MyObj</span> <span class="o">=</span> <span class="p">{</span>
-	<span class="na">a</span><span class="p">:</span> <span class="mi">123</span><span class="p">,</span>
-	<span class="na">str</span><span class="p">:</span> <span class="dl">"</span><span class="s2">string</span><span class="dl">"</span>
-<span class="p">}</span>
+let myObj1: MyObj = {
+	a: 123,
+	str: "string"
+}
 
 
-<span class="kd">let</span> <span class="nx">myObj2</span><span class="p">:</span> <span class="nx">MyObj</span> <span class="o">=</span> <span class="p">{</span>
-	<span class="na">a</span><span class="p">:</span> <span class="mi">456</span><span class="p">,</span>
-	<span class="na">str</span><span class="p">:</span> <span class="dl">"</span><span class="s2">another string</span><span class="dl">"</span>
-<span class="p">}</span>
-</code></pre></div></div>
+let myObj2: MyObj = {
+	a: 456,
+	str: "another string"
+}
+
-<h3 id="compilation">Compilation</h3> +

Compilation

-<p>To be able to work in the browser &amp; node, TypeScript compiles to JavaScript. Now you may have this preconceived notion of the compiled code being unreadable and uglified, but reality is exactly the opposite.</p> +

To be able to work in the browser & node, TypeScript compiles to JavaScript. Now you may have this preconceived notion of the compiled code being unreadable and uglified, but reality is exactly the opposite.

-<p>After type-checking, the compiler will emit very clean and readable code. So this:</p> +

After type-checking, the compiler will emit very clean and readable code. So this:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">x</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> -<span class="kd">let</span> <span class="nx">y</span><span class="p">:</span> <span class="nx">number</span> <span class="o">=</span> <span class="mi">500</span><span class="p">;</span> -<span class="kd">function</span> <span class="nx">getRand</span> <span class="p">(</span><span class="nx">min</span><span class="p">:</span> <span class="nx">number</span><span class="p">,</span> <span class="nx">max</span><span class="p">:</span> <span class="nx">number</span><span class="p">):</span> <span class="nx">number</span> <span class="p">{</span> - <span class="k">return</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">floor</span><span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">*</span> <span class="p">(</span><span class="nx">max</span> <span class="o">-</span> <span class="nx">min</span><span class="p">))</span> <span class="o">+</span> <span class="nx">min</span><span class="p">;</span> -<span class="p">}</span> -<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getRand</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">));</span> -</code></pre></div></div> +
let x: number = 1;
+let y: number = 500;
+function getRand (min: number, max: number): number {
+	return Math.floor(Math.random() * (max - min)) + min;
+}
+console.log(getRand(x, y));
+
-<p>Will compile to this:</p> +

Will compile to this:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">x</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> -<span class="kd">var</span> <span class="nx">y</span> <span class="o">=</span> <span class="mi">500</span><span class="p">;</span> -<span class="kd">function</span> <span class="nx">getRand</span><span class="p">(</span><span class="nx">min</span><span class="p">,</span> <span class="nx">max</span><span class="p">)</span> <span class="p">{</span> - <span class="k">return</span> <span class="nb">Math</span><span class="p">.</span><span class="nx">floor</span><span class="p">(</span><span class="nb">Math</span><span class="p">.</span><span class="nx">random</span><span class="p">()</span> <span class="o">*</span> <span class="p">(</span><span class="nx">max</span> <span class="o">-</span> <span class="nx">min</span><span class="p">))</span> <span class="o">+</span> <span class="nx">min</span><span class="p">;</span> -<span class="p">}</span> -<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">getRand</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">));</span> -</code></pre></div></div> +
var x = 1;
+var y = 500;
+function getRand(min, max) {
+	return Math.floor(Math.random() * (max - min)) + min;
+}
+console.log(getRand(x, y));
+
-<p>Have a look at the <a href="http://www.typescriptlang.org/play/">TypeScript Playground</a> where you can compile TypeScript immediately in your browser. Yes, it’s being compiled in the browser. This is possible since the TypeScript compiler is written in TypeScript.</p> +

Have a look at the TypeScript Playground where you can compile TypeScript immediately in your browser. Yes, it’s being compiled in the browser. This is possible since the TypeScript compiler is written in TypeScript.

-<p>And while you’re at it, you’ll notice 2 things:</p> +

And while you’re at it, you’ll notice 2 things:

-<ul> - <li>TypeScript compiler is really fast!</li> - <li>You can compile your ES6/ES7 code all the way down to ES3. No Babel required.</li> -</ul> +
    +
  • TypeScript compiler is really fast!
  • +
  • You can compile your ES6/ES7 code all the way down to ES3. No Babel required.
  • +
-<blockquote> - <p>You won’t have to use Babel/buble anymore. TypeScript bridges the gap between the recent versions of JavaScript and what’s available on every modern browser, by compiling your code down to even ES3. However, you still have the option to compile to any ES version you like.</p> -</blockquote> +
+

You won’t have to use Babel/buble anymore. TypeScript bridges the gap between the recent versions of JavaScript and what’s available on every modern browser, by compiling your code down to even ES3. However, you still have the option to compile to any ES version you like.

+
-<h2 id="type-inference">Type inference</h2> +

Type inference

-<p>One of the killer features of TypeScript, is a really good type inference. Meaning that sometimes you won’t even have to declare some of the types.</p> +

One of the killer features of TypeScript, is a really good type inference. Meaning that sometimes you won’t even have to declare some of the types.

-<p>For example:</p> +

For example:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> -<span class="kd">let</span> <span class="nx">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="c1">// inferred as a number</span> -<span class="kd">let</span> <span class="nx">str</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">string</span><span class="dl">"</span><span class="p">;</span> <span class="c1">// inferred as a string</span> +

+let a = 1; // inferred as a number
+let str = "string"; // inferred as a string
 
-<span class="c1">// function return type will also be inferred</span>
-<span class="kd">function</span> <span class="nx">add</span> <span class="p">(</span><span class="nx">a</span><span class="p">:</span><span class="nx">number</span><span class="p">,</span> <span class="nx">b</span><span class="p">:</span><span class="nx">number</span><span class="p">)</span> <span class="p">{</span>
-	<span class="k">return</span> <span class="nx">a</span> <span class="o">+</span> <span class="nx">b</span><span class="p">;</span>
-<span class="p">}</span>
+// function return type will also be inferred
+function add (a:number, b:number) {
+	return a + b;
+}
 
-<span class="kd">let</span> <span class="nx">b</span> <span class="o">=</span> <span class="nx">add</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">);</span> <span class="c1">// type inferred as a number</span>
-<span class="kd">let</span> <span class="nx">x</span> <span class="o">=</span> <span class="nx">add</span><span class="p">(</span><span class="nx">c</span><span class="p">,</span> <span class="nx">b</span><span class="p">);</span> <span class="c1">// compiler will produce an error</span>
-</code></pre></div></div>
+let b = add(1, 3); // type inferred as a number
+let x = add(c, b); // compiler will produce an error
+
-<p>Another advanced example:</p> +

Another advanced example:

-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Notice how we won't declare any types:</span> -<span class="kd">function</span> <span class="nx">myFunc</span> <span class="p">(</span><span class="nx">param</span><span class="p">)</span> <span class="p">{</span> - <span class="k">return</span> <span class="p">{</span> - <span class="na">n</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> - <span class="na">str</span><span class="p">:</span> <span class="dl">"</span><span class="s2">myString</span><span class="dl">"</span><span class="p">,</span> - <span class="na">obj</span><span class="p">:</span> <span class="p">{</span> - <span class="na">obj</span><span class="p">:</span> <span class="p">{</span> - <span class="na">obj</span><span class="p">:</span> <span class="p">{</span> - <span class="na">someVal</span><span class="p">:</span> <span class="nx">param</span> <span class="o">&gt;</span> <span class="mi">5</span> <span class="p">?</span> <span class="dl">"</span><span class="s2">myString</span><span class="dl">"</span> <span class="p">:</span> <span class="nx">param</span> <span class="o">&gt;</span> <span class="mi">4</span> <span class="p">?</span> <span class="p">{</span><span class="na">a</span><span class="p">:</span><span class="mi">5</span><span class="p">}</span> <span class="p">:</span> <span class="p">[</span><span class="dl">"</span><span class="s2">myString</span><span class="dl">"</span><span class="p">,</span> <span class="mi">14</span><span class="p">]</span> - <span class="p">}</span> - <span class="p">}</span> - <span class="p">}</span> - <span class="p">}</span> -<span class="p">}</span> -<span class="c1">// hover over someVal</span> -<span class="nx">myFunc</span><span class="p">(</span><span class="mi">10</span><span class="p">).</span><span class="nx">obj</span><span class="p">.</span><span class="nx">obj</span><span class="p">.</span><span class="nx">obj</span><span class="p">.</span><span class="nx">someVal</span> -</code></pre></div></div> +
// Notice how we won't declare any types:
+function myFunc (param) {
+	return {
+		n: 0,
+		str: "myString",
+		obj: {
+			obj: {
+				obj: {
+					someVal: param > 5 ? "myString" : param > 4 ? {a:5} : ["myString", 14]
+				}
+			}
+		}
+	}
+}
+// hover over someVal
+myFunc(10).obj.obj.obj.someVal
+
-<p>Now when hovering over <code class="language-plaintext highlighter-rouge">someVal</code> you’ll notice that it’s type is declared as:</p> +

Now when hovering over someVal you’ll notice that it’s type is declared as:

-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>string | Array&lt;string|number&gt; | {a: number;} -</code></pre></div></div> +
string | Array<string|number> | {a: number;}
+
-<p><a href="https://goo.gl/Zw11Yv">Try it</a></p> +

Try it

-<h2 id="node-and-typescript">Node and TypeScript</h2> +

Node and TypeScript

-<p>Node.JS support was a priority when developing TypeScript. Your TypeScript code can be distributed as a node module, consumed in JavaScript just like any JavaScript module, and consumed in TypeScript with type declarations included, all while writing only once.</p> +

Node.JS support was a priority when developing TypeScript. Your TypeScript code can be distributed as a node module, consumed in JavaScript just like any JavaScript module, and consumed in TypeScript with type declarations included, all while writing only once.

-<h3 id="authoring-and-distributing-typescript-node-modules">Authoring and distributing TypeScript Node Modules</h3> +

Authoring and distributing TypeScript Node Modules

-<p>When compiling your javascript you can tell the compiler to emit type definitions (only type definitions, no logic) in a separate file that can be discoverable by TypeScript, yet does not affect your module when consumed in a JavaScript project (unless your editor wanted to be smart about it).</p> +

When compiling your javascript you can tell the compiler to emit type definitions (only type definitions, no logic) in a separate file that can be discoverable by TypeScript, yet does not affect your module when consumed in a JavaScript project (unless your editor wanted to be smart about it).

-<p>All that you have to do is include the <code class="language-plaintext highlighter-rouge">declaration:true</code> in your <code class="language-plaintext highlighter-rouge">tsconfig.json</code> file:</p> +

All that you have to do is include the declaration:true in your tsconfig.json file:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span> - <span class="dl">"</span><span class="s2">declarations</span><span class="dl">"</span><span class="p">:</span><span class="kc">true</span> -<span class="p">}</span> -</code></pre></div></div> +
{
+	"declarations":true
+}
+
-<p>then refer to this file in your <code class="language-plaintext highlighter-rouge">package.json</code>:</p> +

then refer to this file in your package.json:

-<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span> - <span class="dl">"</span><span class="s2">types</span><span class="dl">"</span><span class="p">:</span><span class="dl">"</span><span class="s2">./dist/index.d.ts</span><span class="dl">"</span> -<span class="p">}</span> -</code></pre></div></div> +
{
+	"types":"./dist/index.d.ts"
+}
+
-<h3 id="consuming-javascript-node-modules-in-typescript">Consuming JavaScript Node Modules In TypeScript</h3> +

Consuming JavaScript Node Modules In TypeScript

-<p>What if you wanted to consume a module that was written in JavaScript? Express for example. Your editor (e.g. VSCode) can only try to have an idea about the imported module, but as we’ve discussed above, tools are actually limited by the dynamic nature of JavaScript.</p> +

What if you wanted to consume a module that was written in JavaScript? Express for example. Your editor (e.g. VSCode) can only try to have an idea about the imported module, but as we’ve discussed above, tools are actually limited by the dynamic nature of JavaScript.

-<p>So your best bet is head to <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">the DefinitelyTyped repository</a> and find if a there’s a type definition for the module you’re consuming.</p> +

So your best bet is head to the DefinitelyTyped repository and find if a there’s a type definition for the module you’re consuming.

-<p>The good news is that <a href="https://github.com/DefinitelyTyped/DefinitelyTyped">the DefinitelyTyped repository</a> have over 3000 modules. Chances are you’re going to find the module you’re about to use.</p> +

The good news is that the DefinitelyTyped repository have over 3000 modules. Chances are you’re going to find the module you’re about to use.

-<h4 id="example-consuming-express-in-typescript">Example: Consuming Express in TypeScript</h4> +

Example: Consuming Express in TypeScript

-<p>Install the types:</p> +

Install the types:

-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npm i --save-dev @types/express -</code></pre></div></div> +
npm i --save-dev @types/express
+
-<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// import</span> -<span class="k">import</span> <span class="p">{</span> <span class="nx">Request</span><span class="p">,</span> <span class="nx">Response</span><span class="p">,</span> <span class="nx">NextFunction</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@types/express</span><span class="dl">"</span><span class="p">;</span> -<span class="c1">// declare</span> -<span class="kd">function</span> <span class="nx">myMiddleWare</span> <span class="p">(</span><span class="nx">req</span><span class="p">:</span> <span class="nx">Request</span><span class="p">,</span> <span class="nx">res</span><span class="p">:</span> <span class="nx">Response</span><span class="p">,</span> <span class="nx">next</span><span class="p">:</span><span class="nx">NextFunction</span><span class="p">)</span> <span class="p">{</span> - <span class="c1">// middleware code</span> -<span class="p">}</span> -</code></pre></div></div> +
// import
+import { Request, Response, NextFunction } from "@types/express";
+// declare
+function myMiddleWare (req: Request, res: Response, next:NextFunction) {
+	// middleware code
+}
+
-<h2 id="react-and-typescript">React and TypeScript</h2> +

React and TypeScript

-<p>TypeScript, being an open-source community driven project, have added support for react in a really nice way.</p> +

TypeScript, being an open-source community driven project, have added support for react in a really nice way.

-<p>Just like you’re going to rename your <code class="language-plaintext highlighter-rouge">.js</code> files to <code class="language-plaintext highlighter-rouge">.ts</code>, your <code class="language-plaintext highlighter-rouge">.jsx</code> files should be <code class="language-plaintext highlighter-rouge">.tsx</code>. And that’s it, now install React’s type declarations from the definitely typed repository, and feel how good it is to have everything in your project to be strong-typed. Yes! Even HTML! and CSS!</p> +

Just like you’re going to rename your .js files to .ts, your .jsx files should be .tsx. And that’s it, now install React’s type declarations from the definitely typed repository, and feel how good it is to have everything in your project to be strong-typed. Yes! Even HTML! and CSS!

-<h2 id="dart-flow-purescript-elm">Dart, Flow, PureScript, Elm</h2> +

Dart, Flow, PureScript, Elm

-<ul> - <li><strong>Flow</strong>: Is a facebook product. However, it’s not a language, it’s just a type-checker. TypeScript does what Flow does in addition to many other features. Also it has a larger community.</li> - <li><strong>Dart</strong>: Although very powerful, but Dart’s syntax is different from JavaScript. I think that’s the main reason why it didn’t catch up with the community as TypeScript did. TypeScript embraced the new ES6/ES7 features and built it’s foundation on top of them.</li> - <li><strong>PureScript</strong> &amp; <strong>Elm</strong>: Are trying to achieve different thing, pure functional programming language, that compiles to JavaScript.</li> -</ul> +
    +
  • Flow: Is a facebook product. However, it’s not a language, it’s just a type-checker. TypeScript does what Flow does in addition to many other features. Also it has a larger community.
  • +
  • Dart: Although very powerful, but Dart’s syntax is different from JavaScript. I think that’s the main reason why it didn’t catch up with the community as TypeScript did. TypeScript embraced the new ES6/ES7 features and built it’s foundation on top of them.
  • +
  • PureScript & Elm: Are trying to achieve different thing, pure functional programming language, that compiles to JavaScript.
  • +
-<h2 id="closing-statement">Closing statement</h2> +

Closing statement

-<p>I’ve been developing with JavaScript for at least 5 years. However, After trying TypeScript for merly 4 months, working with JavaScript feels like walking on thin ice, you may make it for 10 meters or so, but you shouldn’t go any longer.</p> +

I’ve been developing with JavaScript for at least 5 years. However, After trying TypeScript for merly 4 months, working with JavaScript feels like walking on thin ice, you may make it for 10 meters or so, but you shouldn’t go any longer.

-<p>I can now understand why there are so many well-educated developers disliking the dynamic nature of JavaScript.</p> +

I can now understand why there are so many well-educated developers disliking the dynamic nature of JavaScript.

-<h2 id="resources">Resources</h2> +

Resources

-<ul> - <li><a href="http://www.typescriptlang.org/docs/tutorial.html">The official documentation</a>.</li> - <li>Anders Hejlsberg Talks about TypeScript: <a href="http://video.ch9.ms/ch9/4ae3/062c336d-9cf0-498f-ae9a-582b87954ae3/B881_mid.mp4">1</a> <a href="https://www.youtube.com/watch?v=s0ecDXWvLmU">2</a> <a href="https://www.youtube.com/watch?v=eX2PXjj-KDk">3</a>.</li> - <li><a href="http://definitelytyped.org/">Definitely Typed</a>.</li> - <li>Editors and IDEs plugins: <a href="https://github.com/Microsoft/TypeScript-Sublime-Plugin">Sublime Text</a> <a href="https://atom.io/packages/atom-typescript">Atom</a> <a href="https://github.com/palantir/eclipse-typescript">Eclipse</a> <a href="https://github.com/Microsoft/TypeScript/wiki/TypeScript-Editor-Support#vim">Vim</a>.</li> -</ul>
Alex CorviI was introduced to TypeScript when it first came with angular 2. However, I tried to avoid it as much as possible. This was actually the main reason of why I left angular in favor of Vue. “A new quirky front-end language is the last thing I would need,” I thought.
Rust for High-Level Programming Language Developers2017-04-12T05:00:00+00:002017-04-12T05:00:00+00:00/Rust%20for%20High-Level%20Programming%20Language%20Developers<p>So you’ve been doing high-level programming all your life, and you’ve been eyeing Rust for some time now, and you’re not sure where to start (or how to start). Well, this walk-through-like post will guide you through some of the common tasks you preform in high-level languages like JavaScript, Python, or even C#.</p> +]]>Alex CorviRust for High-Level Programming Language Developers2017-04-12T05:00:00+00:002017-04-12T05:00:00+00:00/Rust%20for%20High-Level%20Programming%20Language%20DevelopersSo you’ve been doing high-level programming all your life, and you’ve been eyeing Rust for some time now, and you’re not sure where to start (or how to start). Well, this walk-through-like post will guide you through some of the common tasks you preform in high-level languages like JavaScript, Python, or even C#.

-<h3 id="so-json-in-rust">So, JSON in Rust?</h3> -<h4 id="the-short-answer-is-no-built-in-support-for-json-but">The short answer is ‘no built-in support for JSON but…’</h4> -<p>Well, Rust has no built-in support for JSON objects, but before you let that throw you off, Rust <code class="language-plaintext highlighter-rouge">struct</code>s are ~ 99% identical to JSON objects in their outer structure and the way they are defined and used. Let’s look at an example.</p> +

So, JSON in Rust?

+

The short answer is ‘no built-in support for JSON but…’

+

Well, Rust has no built-in support for JSON objects, but before you let that throw you off, Rust structs are ~ 99% identical to JSON objects in their outer structure and the way they are defined and used. Let’s look at an example.

-<p>Say you want to define a Person JSON object with fields holding things like the <code class="language-plaintext highlighter-rouge">full name</code>, <code class="language-plaintext highlighter-rouge">date of birth</code>, and <code class="language-plaintext highlighter-rouge">gender</code> of a person. Here’s how you’d likely define your object in a language like JavaScript:</p> +

Say you want to define a Person JSON object with fields holding things like the full name, date of birth, and gender of a person. Here’s how you’d likely define your object in a language like JavaScript:

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">person</span> <span class="o">=</span> <span class="p">{</span> - <span class="na">fullName</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Fadi Hanna Al-Kass</span><span class="dl">'</span><span class="p">,</span> - <span class="na">dateOfBirth</span><span class="p">:</span> <span class="dl">'</span><span class="s1">01-01-1990</span><span class="dl">'</span><span class="p">,</span> - <span class="na">gender</span><span class="p">:</span> <span class="dl">'</span><span class="s1">MALE</span><span class="dl">'</span> -<span class="p">};</span> -</code></pre></div></div> +
var person = {
+  fullName: 'Fadi Hanna Al-Kass',
+  dateOfBirth: '01-01-1990',
+  gender: 'MALE'
+};
+
-<p>Here’s how you’d write this in Rust:</p> +

Here’s how you’d write this in Rust:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">// Our pseudo-JSON object skeleton</span> -<span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span> - <span class="n">full_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> - <span class="n">date_of_birth</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> - <span class="n">gender</span><span class="p">:</span> <span class="nb">String</span> -<span class="p">}</span> +
// Our pseudo-JSON object skeleton
+struct Person {
+  full_name: String,
+  date_of_birth: String,
+  gender: String
+}
 
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-    <span class="n">full_name</span><span class="p">:</span> <span class="s">"Fadi Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">(),</span>
-    <span class="n">date_of_birth</span><span class="p">:</span> <span class="s">"01-01-1990"</span><span class="nf">.to_string</span><span class="p">(),</span>
-    <span class="n">gender</span><span class="p">:</span> <span class="s">"MALE"</span><span class="nf">.to_string</span><span class="p">()</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
+fn main () {
+  let person = Person {
+    full_name: "Fadi Hanna Al-Kass".to_string(),
+    date_of_birth: "01-01-1990".to_string(),
+    gender: "MALE".to_string()
+  };
+}
+
-<p>You’ve probably already noticed two differences between the two code snippets:</p> +

You’ve probably already noticed two differences between the two code snippets:

-<ol> - <li>We had to define a skeleton for our pseudo-JSON object.</li> - <li>We used lowerCamelCase with JavaScript and snake_case with our Rust code snippet. This is really nothing more than a naming convention that the Rust compiler will throw a bunch of warnings at you if you don’t follow, but it shouldn’t have an effect on the execution of your program if you so choose not to follow.</li> -</ol> +
    +
  1. We had to define a skeleton for our pseudo-JSON object.
  2. +
  3. We used lowerCamelCase with JavaScript and snake_case with our Rust code snippet. This is really nothing more than a naming convention that the Rust compiler will throw a bunch of warnings at you if you don’t follow, but it shouldn’t have an effect on the execution of your program if you so choose not to follow.
  4. +
-<p>Now back to the first (and perhaps, more obvious) difference. Rust is a very (and I mean very) strongly typed programming language. That said, it needs to own as much information about your object types during the compilation process as possible. Of course, <code class="language-plaintext highlighter-rouge">struct</code>s are no exception, and you can really consider two ways (or more, depending on how imaginational you are) of looking at this: it is either (1) <code class="language-plaintext highlighter-rouge">limiting</code> or (2) <code class="language-plaintext highlighter-rouge">validating</code>. I wouldn’t be putting this post together had I considered strong-typing limiting.</p> +

Now back to the first (and perhaps, more obvious) difference. Rust is a very (and I mean very) strongly typed programming language. That said, it needs to own as much information about your object types during the compilation process as possible. Of course, structs are no exception, and you can really consider two ways (or more, depending on how imaginational you are) of looking at this: it is either (1) limiting or (2) validating. I wouldn’t be putting this post together had I considered strong-typing limiting.

-<blockquote> - <p>You can always replace a strongly typed pseudo-JSON object with a <code class="language-plaintext highlighter-rouge">HashMap</code> to get around the static typing issue, but I’d advice against that, and I believe I can convince you to stick to the <code class="language-plaintext highlighter-rouge">struct</code> approach. You may, at this point, still not think so, but wait until we get to these magical little thingies called <code class="language-plaintext highlighter-rouge">traits</code> and then we’ll see ;-)</p> -</blockquote> +
+

You can always replace a strongly typed pseudo-JSON object with a HashMap to get around the static typing issue, but I’d advice against that, and I believe I can convince you to stick to the struct approach. You may, at this point, still not think so, but wait until we get to these magical little thingies called traits and then we’ll see ;-)

+
-<h3 id="nested-pseudo-json-objects">Nested pseudo-JSON Objects?</h3> -<h4 id="sure-forward-we-go">Sure, forward we go</h4> +

Nested pseudo-JSON Objects?

+

Sure, forward we go

-<p>Let’s design our <code class="language-plaintext highlighter-rouge">Person</code> JSON object in a more modern fashion. Instead of having a field containing the <code class="language-plaintext highlighter-rouge">full_name</code>, we can turn <code class="language-plaintext highlighter-rouge">full_name</code> into a sub-<code class="language-plaintext highlighter-rouge">struct</code> that has two fields (<code class="language-plaintext highlighter-rouge">first_name</code> and <code class="language-plaintext highlighter-rouge">last_name</code>). Instead of storing <code class="language-plaintext highlighter-rouge">date_of_birth</code> as a string that we may, at some point, need to parse down to extract the day, month, and the year from, we can store this information in a <code class="language-plaintext highlighter-rouge">struct</code> with three separate fields. And for our <code class="language-plaintext highlighter-rouge">gender</code> field, we can reference an <code class="language-plaintext highlighter-rouge">enum</code> value.</p> +

Let’s design our Person JSON object in a more modern fashion. Instead of having a field containing the full_name, we can turn full_name into a sub-struct that has two fields (first_name and last_name). Instead of storing date_of_birth as a string that we may, at some point, need to parse down to extract the day, month, and the year from, we can store this information in a struct with three separate fields. And for our gender field, we can reference an enum value.

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">FullName</span> <span class="p">{</span> - <span class="n">first_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> - <span class="n">last_name</span><span class="p">:</span> <span class="nb">String</span> -<span class="p">}</span> +
struct FullName {
+    first_name: String,
+    last_name: String
+}
 
-<span class="k">struct</span> <span class="n">DateOfBirth</span> <span class="p">{</span>
-    <span class="n">day</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>  <span class="c">// 8-bit integer variable</span>
-    <span class="n">month</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>
-    <span class="n">year</span><span class="p">:</span> <span class="nb">i16</span> <span class="c">// 16-bit integer variable</span>
-<span class="p">}</span>
-
-<span class="k">enum</span> <span class="n">Gender</span> <span class="p">{</span>
-    <span class="n">MALE</span><span class="p">,</span>
-    <span class="n">FEMALE</span><span class="p">,</span>
-    <span class="n">NotDisclosed</span>
-<span class="p">}</span>
-
-<span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span>
-  <span class="n">full_name</span><span class="p">:</span> <span class="n">FullName</span><span class="p">,</span>
-  <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">DateOfBirth</span><span class="p">,</span>
-  <span class="n">gender</span><span class="p">:</span> <span class="n">Gender</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-      <span class="n">full_name</span><span class="p">:</span> <span class="n">FullName</span> <span class="p">{</span>
-          <span class="n">first_name</span><span class="p">:</span> <span class="s">"Fadi"</span><span class="nf">.to_string</span><span class="p">(),</span>
-          <span class="n">last_name</span><span class="p">:</span> <span class="s">"Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">()</span>
-      <span class="p">},</span>
-      <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">DateOfBirth</span> <span class="p">{</span>
-          <span class="n">day</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
-          <span class="n">month</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
-          <span class="n">year</span><span class="p">:</span> <span class="mi">1990</span>
-      <span class="p">},</span>
-      <span class="n">gender</span><span class="p">:</span> <span class="nn">Gender</span><span class="p">::</span><span class="n">MALE</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>Our pseudo-JSON object is now looking much cleaner and even easier to utilize. Speaking of utilization, how do we reference our fields? Well, you’ve probably guessed it already. Yes, it’s the dot operator. If you’re interested in, say, printing the full name of your Person object, here’s how you’d do that:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">// The following line of code goes inside your main function right after</span>
-<span class="c">// your person object has been instantiated, or really anywhere after the</span>
-<span class="c">// object has been declared.</span>
-
-<span class="nd">println!</span><span class="p">(</span><span class="s">"{} {}"</span><span class="p">,</span> <span class="n">person</span><span class="py">.full_name.first_name</span><span class="p">,</span> <span class="n">person</span><span class="py">.full_name.last_name</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>and you’re probably seeing a problem here already. It would be absolutely tedious to use this approach to print out the full name of a person especially if you were to do this from multiple places in your program let alone the fact the way the print is done looks really primitive. There must be a different (perhaps, even, better) way you say. You bet there is. In fact, there not only is but are many ways you can go about handling this issue, which one of which would be the use of <code class="language-plaintext highlighter-rouge">traits</code>. A trait is a programmatical way of telling the compiler how to carry out specific functionalities during the build process. We’re going to use one here and learn how to write our own further below. The trait we’re about to use in a moment is called the <code class="language-plaintext highlighter-rouge">Debug</code> trait which basically sets out a specific printing layout for your defined <code class="language-plaintext highlighter-rouge">enum</code>, <code class="language-plaintext highlighter-rouge">struct</code> or what have you.</p>
-
-<p>If you simply add <code class="language-plaintext highlighter-rouge">#[derive(Debug)]</code> right on top of your <code class="language-plaintext highlighter-rouge">FullName</code> <code class="language-plaintext highlighter-rouge">struct</code> definition: i.e.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">#[derive(Debug)]</span>
-<span class="k">struct</span> <span class="n">FullName</span> <span class="p">{</span>
-    <span class="n">first_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
-    <span class="n">last_name</span><span class="p">:</span> <span class="nb">String</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>and replace:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">println!</span><span class="p">(</span><span class="s">"{} {}"</span><span class="p">,</span> <span class="n">person</span><span class="py">.full_name.first_name</span><span class="p">,</span> <span class="n">person</span><span class="py">.full_name.last_name</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>with:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">println!</span><span class="p">(</span><span class="s">"{:?}"</span><span class="p">,</span> <span class="n">person</span><span class="py">.full_name</span><span class="p">);</span>
-</code></pre></div></div>
-
-<p>You’ll end up with:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">FullName</span> <span class="p">{</span> <span class="n">first_name</span><span class="p">:</span> <span class="s">"Fadi"</span><span class="p">,</span> <span class="n">last_name</span><span class="p">:</span> <span class="s">"Hanna Al-Kass"</span> <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Cool, isn’t it? Well, it gets even cooler in a bit.</p>
-
-<p>But hang on a second, why did I have to replace <code class="language-plaintext highlighter-rouge">{}</code> with <code class="language-plaintext highlighter-rouge">{:?}</code> in my <code class="language-plaintext highlighter-rouge">println</code> statement? Or an even more proper question to ask is: what is the difference between the two?
-Well, so Rust has two ways of printing out stuff (there might be even more ways I am yet to discover!): a (1) <code class="language-plaintext highlighter-rouge">Display</code> and a <code class="language-plaintext highlighter-rouge">Debug</code>. <code class="language-plaintext highlighter-rouge">Display</code> is what you’d probably want to use to allow the program to communicate some meaningful output to your user, and <code class="language-plaintext highlighter-rouge">Debug</code> is what you could use during the development process. These two <code class="language-plaintext highlighter-rouge">traits</code> can co-exist without overlapping each other. By that I mean you can allow your object to print something with <code class="language-plaintext highlighter-rouge">{}</code> and something entirely different with <code class="language-plaintext highlighter-rouge">{:?}</code>, but that’s to be covered when we get down to writing our own <code class="language-plaintext highlighter-rouge">trait</code>s.</p>
-
-<p>So is it possible to use <code class="language-plaintext highlighter-rouge">#[derive(Debug)]</code> to print out nested objects? Yes, it is, and following is how. Simply add <code class="language-plaintext highlighter-rouge">#[derive(Debug)]</code> right on top of your main object and every object that’s part of it and then print the object as a whole by passing it to a  <code class="language-plaintext highlighter-rouge">println</code> function using the <code class="language-plaintext highlighter-rouge">{:?}</code> notation, i.e.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">#[derive(Debug)]</span>
-<span class="k">struct</span> <span class="n">FullName</span> <span class="p">{</span>
-    <span class="n">first_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
-    <span class="n">last_name</span><span class="p">:</span> <span class="nb">String</span>
-<span class="p">}</span>
-
-<span class="nd">#[derive(Debug)]</span>
-<span class="k">struct</span> <span class="n">DateOfBirth</span> <span class="p">{</span>
-    <span class="n">day</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>  <span class="c">// 8-bit integer variable</span>
-    <span class="n">month</span><span class="p">:</span> <span class="nb">i8</span><span class="p">,</span>
-    <span class="n">year</span><span class="p">:</span> <span class="nb">i16</span> <span class="c">// 16-bit integer variable</span>
-<span class="p">}</span>
-
-<span class="nd">#[derive(Debug)]</span>
-<span class="k">enum</span> <span class="n">Gender</span> <span class="p">{</span>
-    <span class="n">MALE</span><span class="p">,</span>
-    <span class="n">FEMALE</span><span class="p">,</span>
-    <span class="n">NotDisclosed</span>
-<span class="p">}</span>
-
-<span class="nd">#[derive(Debug)]</span>
-<span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span>
-  <span class="n">full_name</span><span class="p">:</span> <span class="n">FullName</span><span class="p">,</span>
-  <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">DateOfBirth</span><span class="p">,</span>
-  <span class="n">gender</span><span class="p">:</span> <span class="n">Gender</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="n">Person</span> <span class="p">{</span>
-      <span class="n">full_name</span><span class="p">:</span> <span class="n">FullName</span> <span class="p">{</span>
-          <span class="n">first_name</span><span class="p">:</span> <span class="s">"Fadi"</span><span class="nf">.to_string</span><span class="p">(),</span>
-          <span class="n">last_name</span><span class="p">:</span> <span class="s">"Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">()</span>
-      <span class="p">},</span>
-      <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">DateOfBirth</span> <span class="p">{</span>
-          <span class="n">day</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
-          <span class="n">month</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
-          <span class="n">year</span><span class="p">:</span> <span class="mi">1990</span>
-      <span class="p">},</span>
-      <span class="n">gender</span><span class="p">:</span> <span class="nn">Gender</span><span class="p">::</span><span class="n">MALE</span>
-  <span class="p">};</span>
-  <span class="nd">println!</span><span class="p">(</span><span class="s">"{:?}"</span><span class="p">,</span> <span class="n">person</span><span class="p">);</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And your output will look like:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Person</span> <span class="p">{</span> <span class="n">full_name</span><span class="p">:</span> <span class="n">FullName</span> <span class="p">{</span> <span class="n">first_name</span><span class="p">:</span> <span class="s">"Fadi"</span><span class="p">,</span> <span class="n">last_name</span><span class="p">:</span> <span class="s">"Hanna Al-Kass"</span> <span class="p">},</span> <span class="n">date_of_birth</span><span class="p">:</span> <span class="n">DateOfBirth</span> <span class="p">{</span> <span class="n">day</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="n">month</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="n">year</span><span class="p">:</span> <span class="mi">1990</span> <span class="p">},</span> <span class="n">gender</span><span class="p">:</span> <span class="n">MALE</span> <span class="p">}</span>
-</code></pre></div></div>
-
-<p>Our output is looking pretty verbose already, and you may not like that. Is there a way to manipulate this output in terms of re-arranging its layout or limiting the amount of information being displayed? You bet there is, and it’s through writing our own <code class="language-plaintext highlighter-rouge">Debug</code> <code class="language-plaintext highlighter-rouge">trait</code> instead of using a <code class="language-plaintext highlighter-rouge">derive</code>d one. I think it’s better to introduce one more thing right before we get down to business with <code class="language-plaintext highlighter-rouge">trait</code>s, and that is Rust’s <code class="language-plaintext highlighter-rouge">OOP</code>-like paradigm. I call it <code class="language-plaintext highlighter-rouge">OOP</code>-like because Rust doesn’t consider itself an Object-Oriented Programming Language, but sure that in no way means we can’t do <code class="language-plaintext highlighter-rouge">OOP</code> in Rust. It just means <code class="language-plaintext highlighter-rouge">OOP</code> is done differently. To be more precise, <code class="language-plaintext highlighter-rouge">OOP</code> in Rust is done in a way Rust wouldn’t consider <code class="language-plaintext highlighter-rouge">OOP</code>.</p>
-
-<p>Up until now, we’ve only been working with <code class="language-plaintext highlighter-rouge">struct</code>s and <code class="language-plaintext highlighter-rouge">enum</code>s. You’ve probably already noticed that we used them to store data, but no logic (constructors, functions, destructors, etc) was added to them. That’s because that’s not where the functions go. before I further explain this, let’s look at a tiny Python class and discuss how its alternative can be written in Rust.
-Say you have a <code class="language-plaintext highlighter-rouge">Person</code> <code class="language-plaintext highlighter-rouge">class</code> with a constructor that takes a <code class="language-plaintext highlighter-rouge">first_name</code> and a <code class="language-plaintext highlighter-rouge">last_name</code> and provides two separate getter functions that give you these two string values whenever you need them. You’d write your class something as follows:</p>
-
-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Person</span><span class="p">:</span>
-  <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">firstName</span><span class="p">,</span> <span class="n">lastName</span><span class="p">):</span>
-    <span class="bp">self</span><span class="p">.</span><span class="n">firstName</span> <span class="o">=</span> <span class="n">firstName</span>
-    <span class="bp">self</span><span class="p">.</span><span class="n">lastName</span> <span class="o">=</span> <span class="n">lastName</span>
-  <span class="k">def</span> <span class="nf">getFirstName</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
-    <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">firstName</span>
-  <span class="k">def</span> <span class="nf">getLastName</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
-    <span class="k">return</span> <span class="bp">self</span><span class="p">.</span><span class="n">lastName</span>
-</code></pre></div></div>
-
-<p>Notice how we have our fields and functions mixed together inside a single class. Rust separates the two. You’d have your fields defined inside a <code class="language-plaintext highlighter-rouge">struct</code> and an <code class="language-plaintext highlighter-rouge">impl</code> containing all relevant functions. So, when interpreted, our Python class would look in Rust as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">Person</span> <span class="p">{</span>
-    <span class="n">first_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span>
-    <span class="n">last_name</span><span class="p">:</span> <span class="nb">String</span>
-<span class="p">}</span>
-
-<span class="k">impl</span> <span class="n">Person</span> <span class="p">{</span>
-    <span class="k">fn</span> <span class="nf">new</span> <span class="p">(</span><span class="n">first_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> <span class="n">last_name</span><span class="p">:</span> <span class="nb">String</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Person</span> <span class="p">{</span>
-        <span class="k">return</span> <span class="n">Person</span> <span class="p">{</span>
-            <span class="n">first_name</span><span class="p">:</span> <span class="n">first_name</span><span class="p">,</span>
-            <span class="n">last_name</span><span class="p">:</span> <span class="n">last_name</span>
-        <span class="p">};</span>
-    <span class="p">}</span>
-    <span class="k">fn</span> <span class="nf">get_first_name</span> <span class="p">(</span><span class="o">&amp;</span><span class="k">self</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="o">&amp;</span><span class="nb">str</span> <span class="p">{</span>
-        <span class="k">return</span> <span class="o">&amp;</span><span class="k">self</span><span class="py">.first_name</span><span class="p">;</span>
-    <span class="p">}</span>
-
-    <span class="k">fn</span> <span class="nf">get_last_name</span> <span class="p">(</span><span class="o">&amp;</span><span class="k">self</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="o">&amp;</span><span class="nb">str</span> <span class="p">{</span>
-        <span class="k">return</span> <span class="o">&amp;</span><span class="k">self</span><span class="py">.last_name</span>
-    <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>And to instantiate the object and access/utilize its functions, we do the following:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">person</span> <span class="o">=</span> <span class="nn">Person</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="s">"Fadi"</span><span class="nf">.to_string</span><span class="p">(),</span> <span class="s">"Hanna Al-Kass"</span><span class="nf">.to_string</span><span class="p">());</span>
-<span class="nd">println!</span><span class="p">(</span><span class="s">"{}, {}"</span><span class="p">,</span> <span class="n">person</span><span class="nf">.get_last_name</span><span class="p">(),</span> <span class="n">person</span><span class="nf">.get_first_name</span><span class="p">());</span>
-</code></pre></div></div>
-
-<p>You’ve probably already looked at the code and thought to yourself “aha, <code class="language-plaintext highlighter-rouge">Person::new()</code> must be the constructor” to which you’d definitely be right. however, one thing you need to keep in mind is that Rust has no concept of a <code class="language-plaintext highlighter-rouge">constructor</code> per se. Instead, we define a static function that we use to instantiate our object. This also means <code class="language-plaintext highlighter-rouge">new</code> is not a keyword nor is it the required name of your entry point to your object; it can really be anything but <code class="language-plaintext highlighter-rouge">new</code> is the convention.</p>
-
-<blockquote>
-  <p>In short, your class constructor is a static function located inside an <code class="language-plaintext highlighter-rouge">impl</code> and turns an object of the type of the class you’re instantiating (Person in our case).</p>
-</blockquote>
-
-<h3 id="traits">Traits</h3>
-<h4 id="if-this-doesnt-turn-you-into-a-rust-fanatic-i-dont-think-anything-will-sad--">If this doesn’t turn you into a Rust fanatic, I don’t think anything will. <em>Sad :-(</em></h4>
-
-<p>A <code class="language-plaintext highlighter-rouge">trait</code> is nothing but a language feature that tells the compiler about a type-specific functionality. The definition of a <code class="language-plaintext highlighter-rouge">trait</code> may be confusing as heck to you, but it’ll all settle for you with the first example or two.</p>
-
-<p>Remember how we were talking about classes with constructors, functions, and destructors? Well, we’ve already discussed how constructors and functions are done in Rust. Let’s talk a little about destructors. A <code class="language-plaintext highlighter-rouge">destructor</code> is a class function that invokes itself once the class is out of scope. In some low-level programming languages like C++, a class destructor is normally used to deallocate all allocated memory and preform some house cleaning. Rust has an <code class="language-plaintext highlighter-rouge">impl</code> destruction functionality (<code class="language-plaintext highlighter-rouge">trait</code>) called <code class="language-plaintext highlighter-rouge">Drop</code>. Let’s look at how this trait can be implemented and invoked:</p>
-
-<p>Let’s say you have a <code class="language-plaintext highlighter-rouge">Response</code> object you return to a HTTP validation layer that sends it to an end-client. Once this operation is complete, you have no business in maintaining this <code class="language-plaintext highlighter-rouge">Response</code> object, so it’ll delete itself once it’s out of scope. Let’s start by defining this structure:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">Response</span> <span class="p">{</span>
-  <span class="n">code</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span>
-  <span class="n">message</span><span class="p">:</span> <span class="nb">String</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="n">Response</span> <span class="p">{</span>
-    <span class="n">code</span><span class="p">:</span> <span class="mi">200</span><span class="p">,</span>
-    <span class="n">message</span><span class="p">:</span> <span class="s">"OK"</span><span class="nf">.to_string</span><span class="p">()</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>Now let’s add a <code class="language-plaintext highlighter-rouge">Drop</code> <code class="language-plaintext highlighter-rouge">trait</code> to our object and see when <code class="language-plaintext highlighter-rouge">Drop</code> is invoked:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">impl</span> <span class="n">Drop</span> <span class="k">for</span> <span class="n">Response</span> <span class="p">{</span>
-  <span class="k">fn</span> <span class="k">drop</span> <span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span> <span class="k">self</span><span class="p">)</span> <span class="p">{</span>
-    <span class="nd">println!</span><span class="p">(</span><span class="s">"I ran out of scope. I'm about to be destroyed"</span><span class="p">)</span>
-  <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>If you try to run the complete program now, i.e.:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">Response</span> <span class="p">{</span>
-  <span class="n">code</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span>
-  <span class="n">message</span><span class="p">:</span> <span class="nb">String</span>
-<span class="p">}</span>
-
-<span class="k">impl</span> <span class="n">Drop</span> <span class="k">for</span> <span class="n">Response</span> <span class="p">{</span>
-  <span class="k">fn</span> <span class="k">drop</span> <span class="p">(</span><span class="o">&amp;</span><span class="k">mut</span> <span class="k">self</span><span class="p">)</span> <span class="p">{</span>
-    <span class="nd">println!</span><span class="p">(</span><span class="s">"I ran out of scope. I'm about to be destroyed"</span><span class="p">)</span>
-  <span class="p">}</span>
-<span class="p">}</span>
-
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="n">Response</span> <span class="p">{</span>
-    <span class="n">code</span><span class="p">:</span> <span class="mi">200</span><span class="p">,</span>
-    <span class="n">message</span><span class="p">:</span> <span class="s">"OK"</span><span class="nf">.to_string</span><span class="p">()</span>
-  <span class="p">};</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>You’ll see the following output right before the program finishes executing:</p>
-
-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>I ran out of scope. I'm about to be destroyed
-</code></pre></div></div>
-
-<p>Let’s look at another example.
-If you’ve ever done any scientific computation in Python, chances are you’ve overloaded some of the arithmetic operations (<code class="language-plaintext highlighter-rouge">+</code>, <code class="language-plaintext highlighter-rouge">-</code>, <code class="language-plaintext highlighter-rouge">*</code>, <code class="language-plaintext highlighter-rouge">/</code>, <code class="language-plaintext highlighter-rouge">%</code>, etc). A vector class with <code class="language-plaintext highlighter-rouge">+</code> overloaded would look something like the following:</p>
-
-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Vector</span><span class="p">:</span>
-  <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
-    <span class="bp">self</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="n">a</span>
-    <span class="bp">self</span><span class="p">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">b</span>
-  <span class="k">def</span> <span class="nf">__add__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">otherVector</span><span class="p">):</span>
-    <span class="k">return</span> <span class="n">Vector</span><span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">a</span> <span class="o">+</span> <span class="n">otherVector</span><span class="p">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="p">.</span><span class="n">b</span> <span class="o">+</span> <span class="n">otherVector</span><span class="p">.</span><span class="n">b</span><span class="p">)</span>
-  <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
-    <span class="k">return</span> <span class="s">"Vector(%s, %s)"</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="p">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="p">.</span><span class="n">b</span><span class="p">)</span>
-</code></pre></div></div>
-
-<p>And if you were to add two <code class="language-plaintext highlighter-rouge">Vector</code> objects together, you’d so something like the following:</p>
-
-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">v1</span> <span class="o">=</span> <span class="n">Vector</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
-<span class="n">v2</span> <span class="o">=</span> <span class="n">Vector</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span>
-<span class="n">v3</span> <span class="o">=</span> <span class="n">v1</span> <span class="o">+</span> <span class="n">v2</span>
-</code></pre></div></div>
-
-<p>And print the result as follows:</p>
-
-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">print</span><span class="p">(</span><span class="n">v3</span><span class="p">)</span>
-</code></pre></div></div>
-
-<p>This will print the following:</p>
-
-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Vector</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
-</code></pre></div></div>
-
-<p>Hmm.. Let’s see how we could go about implementing this in Rust. First, we’d need to somehow find a way to add objects (i.e., overload the <code class="language-plaintext highlighter-rouge">+</code> operator). Second, we’d need to be able to give our object to <code class="language-plaintext highlighter-rouge">println</code> and see it print something like <code class="language-plaintext highlighter-rouge">Vector(#, #)</code>. Lucky for us, both of these features are available as <code class="language-plaintext highlighter-rouge">trait</code>s we can implement. Let’s chase them one at a time. We’ll start with the <code class="language-plaintext highlighter-rouge">Add</code> <code class="language-plaintext highlighter-rouge">trait</code>.</p>
-
-<p>Here’s our Rust <code class="language-plaintext highlighter-rouge">Vector</code> object:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">Vector</span> <span class="p">{</span>
-  <span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span>
-  <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>Then we add the <code class="language-plaintext highlighter-rouge">constructor</code>:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">impl</span> <span class="n">Vector</span> <span class="p">{</span>
-    <span class="k">fn</span> <span class="nf">new</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Vector</span> <span class="p">{</span>
-        <span class="k">return</span> <span class="n">Vector</span> <span class="p">{</span>
-            <span class="n">a</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span>
-            <span class="n">b</span><span class="p">:</span> <span class="n">b</span>
-        <span class="p">};</span>
-    <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
-
-<p>We, then, add the <code class="language-plaintext highlighter-rouge">+</code> operation overloaded to our <code class="language-plaintext highlighter-rouge">Vector</code> <code class="language-plaintext highlighter-rouge">struct</code> as follows:</p>
-
-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">ops</span><span class="p">::</span><span class="nb">Add</span><span class="p">;</span>
-
-<span class="k">impl</span> <span class="nb">Add</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span>
-  <span class="k">type</span> <span class="n">Output</span> <span class="o">=</span> <span class="n">Vector</span><span class="p">;</span>
-  <span class="k">fn</span> <span class="nf">add</span> <span class="p">(</span><span class="k">self</span><span class="p">,</span> <span class="n">other_vector</span><span class="p">:</span> <span class="n">Vector</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Vector</span> <span class="p">{</span>
-    <span class="k">return</span> <span class="n">Vector</span> <span class="p">{</span>
-      <span class="n">a</span><span class="p">:</span> <span class="k">self</span><span class="py">.a</span> <span class="o">+</span> <span class="n">other_vector</span><span class="py">.a</span><span class="p">,</span>
-      <span class="n">b</span><span class="p">:</span> <span class="k">self</span><span class="py">.b</span> <span class="o">+</span> <span class="n">other_vector</span><span class="py">.b</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
+struct DateOfBirth {
+    day: i8,  // 8-bit integer variable
+    month: i8,
+    year: i16 // 16-bit integer variable
+}
+
+enum Gender {
+    MALE,
+    FEMALE,
+    NotDisclosed
+}
+
+struct Person {
+  full_name: FullName,
+  date_of_birth: DateOfBirth,
+  gender: Gender
+}
+
+fn main () {
+  let person = Person {
+      full_name: FullName {
+          first_name: "Fadi".to_string(),
+          last_name: "Hanna Al-Kass".to_string()
+      },
+      date_of_birth: DateOfBirth {
+          day: 1,
+          month: 1,
+          year: 1990
+      },
+      gender: Gender::MALE
+  };
+}
+
+ +

Our pseudo-JSON object is now looking much cleaner and even easier to utilize. Speaking of utilization, how do we reference our fields? Well, you’ve probably guessed it already. Yes, it’s the dot operator. If you’re interested in, say, printing the full name of your Person object, here’s how you’d do that:

+ +
// The following line of code goes inside your main function right after
+// your person object has been instantiated, or really anywhere after the
+// object has been declared.
+
+println!("{} {}", person.full_name.first_name, person.full_name.last_name);
+
+ +

and you’re probably seeing a problem here already. It would be absolutely tedious to use this approach to print out the full name of a person especially if you were to do this from multiple places in your program let alone the fact the way the print is done looks really primitive. There must be a different (perhaps, even, better) way you say. You bet there is. In fact, there not only is but are many ways you can go about handling this issue, which one of which would be the use of traits. A trait is a programmatical way of telling the compiler how to carry out specific functionalities during the build process. We’re going to use one here and learn how to write our own further below. The trait we’re about to use in a moment is called the Debug trait which basically sets out a specific printing layout for your defined enum, struct or what have you.

+ +

If you simply add #[derive(Debug)] right on top of your FullName struct definition: i.e.:

+ +
#[derive(Debug)]
+struct FullName {
+    first_name: String,
+    last_name: String
+}
+
+ +

and replace:

+ +
println!("{} {}", person.full_name.first_name, person.full_name.last_name);
+
+ +

with:

+ +
println!("{:?}", person.full_name);
+
+ +

You’ll end up with:

+ +
FullName { first_name: "Fadi", last_name: "Hanna Al-Kass" }
+
+ +

Cool, isn’t it? Well, it gets even cooler in a bit.

+ +

But hang on a second, why did I have to replace {} with {:?} in my println statement? Or an even more proper question to ask is: what is the difference between the two? +Well, so Rust has two ways of printing out stuff (there might be even more ways I am yet to discover!): a (1) Display and a Debug. Display is what you’d probably want to use to allow the program to communicate some meaningful output to your user, and Debug is what you could use during the development process. These two traits can co-exist without overlapping each other. By that I mean you can allow your object to print something with {} and something entirely different with {:?}, but that’s to be covered when we get down to writing our own traits.

+ +

So is it possible to use #[derive(Debug)] to print out nested objects? Yes, it is, and following is how. Simply add #[derive(Debug)] right on top of your main object and every object that’s part of it and then print the object as a whole by passing it to a println function using the {:?} notation, i.e.:

+ +
#[derive(Debug)]
+struct FullName {
+    first_name: String,
+    last_name: String
+}
+
+#[derive(Debug)]
+struct DateOfBirth {
+    day: i8,  // 8-bit integer variable
+    month: i8,
+    year: i16 // 16-bit integer variable
+}
+
+#[derive(Debug)]
+enum Gender {
+    MALE,
+    FEMALE,
+    NotDisclosed
+}
+
+#[derive(Debug)]
+struct Person {
+  full_name: FullName,
+  date_of_birth: DateOfBirth,
+  gender: Gender
+}
+
+fn main () {
+  let person = Person {
+      full_name: FullName {
+          first_name: "Fadi".to_string(),
+          last_name: "Hanna Al-Kass".to_string()
+      },
+      date_of_birth: DateOfBirth {
+          day: 1,
+          month: 1,
+          year: 1990
+      },
+      gender: Gender::MALE
+  };
+  println!("{:?}", person);
+}
+
+ +

And your output will look like:

+ +
Person { full_name: FullName { first_name: "Fadi", last_name: "Hanna Al-Kass" }, date_of_birth: DateOfBirth { day: 1, month: 1, year: 1990 }, gender: MALE }
+
+ +

Our output is looking pretty verbose already, and you may not like that. Is there a way to manipulate this output in terms of re-arranging its layout or limiting the amount of information being displayed? You bet there is, and it’s through writing our own Debug trait instead of using a derived one. I think it’s better to introduce one more thing right before we get down to business with traits, and that is Rust’s OOP-like paradigm. I call it OOP-like because Rust doesn’t consider itself an Object-Oriented Programming Language, but sure that in no way means we can’t do OOP in Rust. It just means OOP is done differently. To be more precise, OOP in Rust is done in a way Rust wouldn’t consider OOP.

+ +

Up until now, we’ve only been working with structs and enums. You’ve probably already noticed that we used them to store data, but no logic (constructors, functions, destructors, etc) was added to them. That’s because that’s not where the functions go. before I further explain this, let’s look at a tiny Python class and discuss how its alternative can be written in Rust. +Say you have a Person class with a constructor that takes a first_name and a last_name and provides two separate getter functions that give you these two string values whenever you need them. You’d write your class something as follows:

+ +
class Person:
+  def __init__(self, firstName, lastName):
+    self.firstName = firstName
+    self.lastName = lastName
+  def getFirstName(self):
+    return self.firstName
+  def getLastName(self):
+    return self.lastName
+
+ +

Notice how we have our fields and functions mixed together inside a single class. Rust separates the two. You’d have your fields defined inside a struct and an impl containing all relevant functions. So, when interpreted, our Python class would look in Rust as follows:

+ +
struct Person {
+    first_name: String,
+    last_name: String
+}
+
+impl Person {
+    fn new (first_name: String, last_name: String) -> Person {
+        return Person {
+            first_name: first_name,
+            last_name: last_name
+        };
+    }
+    fn get_first_name (&self) -> &str {
+        return &self.first_name;
+    }
+
+    fn get_last_name (&self) -> &str {
+        return &self.last_name
+    }
+}
+
+ +

And to instantiate the object and access/utilize its functions, we do the following:

+ +
let person = Person::new("Fadi".to_string(), "Hanna Al-Kass".to_string());
+println!("{}, {}", person.get_last_name(), person.get_first_name());
+
+ +

You’ve probably already looked at the code and thought to yourself “aha, Person::new() must be the constructor” to which you’d definitely be right. however, one thing you need to keep in mind is that Rust has no concept of a constructor per se. Instead, we define a static function that we use to instantiate our object. This also means new is not a keyword nor is it the required name of your entry point to your object; it can really be anything but new is the convention.

+ +
+

In short, your class constructor is a static function located inside an impl and turns an object of the type of the class you’re instantiating (Person in our case).

+
+ +

Traits

+

If this doesn’t turn you into a Rust fanatic, I don’t think anything will. Sad :-(

+ +

A trait is nothing but a language feature that tells the compiler about a type-specific functionality. The definition of a trait may be confusing as heck to you, but it’ll all settle for you with the first example or two.

+ +

Remember how we were talking about classes with constructors, functions, and destructors? Well, we’ve already discussed how constructors and functions are done in Rust. Let’s talk a little about destructors. A destructor is a class function that invokes itself once the class is out of scope. In some low-level programming languages like C++, a class destructor is normally used to deallocate all allocated memory and preform some house cleaning. Rust has an impl destruction functionality (trait) called Drop. Let’s look at how this trait can be implemented and invoked:

+ +

Let’s say you have a Response object you return to a HTTP validation layer that sends it to an end-client. Once this operation is complete, you have no business in maintaining this Response object, so it’ll delete itself once it’s out of scope. Let’s start by defining this structure:

+ +
struct Response {
+  code: i32,
+  message: String
+}
+
+fn main () {
+  let res = Response {
+    code: 200,
+    message: "OK".to_string()
+  };
+}
+
+ +

Now let’s add a Drop trait to our object and see when Drop is invoked:

+ +
impl Drop for Response {
+  fn drop (&mut self) {
+    println!("I ran out of scope. I'm about to be destroyed")
+  }
+}
+
+ +

If you try to run the complete program now, i.e.:

+ +
struct Response {
+  code: i32,
+  message: String
+}
+
+impl Drop for Response {
+  fn drop (&mut self) {
+    println!("I ran out of scope. I'm about to be destroyed")
+  }
+}
+
+fn main () {
+  let res = Response {
+    code: 200,
+    message: "OK".to_string()
+  };
+}
+
+ +

You’ll see the following output right before the program finishes executing:

+ +
I ran out of scope. I'm about to be destroyed
+
+ +

Let’s look at another example. +If you’ve ever done any scientific computation in Python, chances are you’ve overloaded some of the arithmetic operations (+, -, *, /, %, etc). A vector class with + overloaded would look something like the following:

+ +
class Vector:
+  def __init__(self, a, b):
+    self.a = a
+    self.b = b
+  def __add__(self, otherVector):
+    return Vector(self.a + otherVector.a, self.b + otherVector.b)
+  def __str__(self):
+    return "Vector(%s, %s)" % (self.a, self.b)
+
+ +

And if you were to add two Vector objects together, you’d so something like the following:

+ +
v1 = Vector(1, 2)
+v2 = Vector(5, 7)
+v3 = v1 + v2
+
+ +

And print the result as follows:

+ +
print(v3)
+
+ +

This will print the following:

+ +
Vector(6, 9)
+
+ +

Hmm.. Let’s see how we could go about implementing this in Rust. First, we’d need to somehow find a way to add objects (i.e., overload the + operator). Second, we’d need to be able to give our object to println and see it print something like Vector(#, #). Lucky for us, both of these features are available as traits we can implement. Let’s chase them one at a time. We’ll start with the Add trait.

+ +

Here’s our Rust Vector object:

+ +
struct Vector {
+  a: i32,
+  b: i32
+}
+
+ +

Then we add the constructor:

+ +
impl Vector {
+    fn new (a: i32, b: i32) -> Vector {
+        return Vector {
+            a: a,
+            b: b
+        };
+    }
+}
+
+ +

We, then, add the + operation overloaded to our Vector struct as follows:

+ +
use std::ops::Add;
+
+impl Add for Vector {
+  type Output = Vector;
+  fn add (self, other_vector: Vector) -> Vector {
+    return Vector {
+      a: self.a + other_vector.a,
+      b: self.b + other_vector.b
+    };
+  }
+}
+
-<p>At this point, we can have the following in our <code class="language-plaintext highlighter-rouge">main</code> function:</p> +

At this point, we can have the following in our main function:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">v1</span> <span class="o">=</span> <span class="nn">Vector</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span> -<span class="k">let</span> <span class="n">v2</span> <span class="o">=</span> <span class="nn">Vector</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">);</span> -<span class="k">let</span> <span class="n">v3</span> <span class="o">=</span> <span class="n">v1</span> <span class="o">+</span> <span class="n">v2</span><span class="p">;</span> -</code></pre></div></div> +
let v1 = Vector::new(1, 2);
+let v2 = Vector::new(5, 7);
+let v3 = v1 + v2;
+
-<p>But we can’t print quite yet. Let’s implement this:</p> +

But we can’t print quite yet. Let’s implement this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::{</span><span class="n">Debug</span><span class="p">,</span> <span class="n">Formatter</span><span class="p">,</span> <span class="n">Result</span><span class="p">};</span> -<span class="k">impl</span> <span class="n">Debug</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span> - <span class="k">fn</span> <span class="nf">fmt</span><span class="p">(</span><span class="o">&amp;</span><span class="k">self</span><span class="p">,</span> <span class="n">f</span><span class="p">:</span> <span class="o">&amp;</span><span class="k">mut</span> <span class="n">Formatter</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Result</span> <span class="p">{</span> - <span class="k">return</span> <span class="nd">write!</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s">"Vector({}, {})"</span><span class="p">,</span> <span class="k">self</span><span class="py">.a</span><span class="p">,</span> <span class="k">self</span><span class="py">.b</span><span class="p">);</span> - <span class="p">}</span> -<span class="p">}</span> -</code></pre></div></div> +
use std::fmt::{Debug, Formatter, Result};
+impl Debug for Vector {
+  fn fmt(&self, f: &mut Formatter) -> Result {
+    return write!(f, "Vector({}, {})", self.a, self.b);
+  }
+}
+
-<p>Now we can print <code class="language-plaintext highlighter-rouge">v3</code> as follows:</p> +

Now we can print v3 as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">println!</span><span class="p">(</span><span class="s">"{:?}"</span><span class="p">,</span> <span class="n">v3</span><span class="p">);</span> -</code></pre></div></div> +
println!("{:?}", v3);
+
-<p>And get the following output:</p> +

And get the following output:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Vector</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span> -</code></pre></div></div> +
Vector(6, 9)
+
-<p>Your final program should look like the following:</p> +

Your final program should look like the following:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">Vector</span> <span class="p">{</span> - <span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> - <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span> -<span class="p">}</span> +
struct Vector {
+  a: i32,
+  b: i32
+}
 
-<span class="k">impl</span> <span class="n">Vector</span> <span class="p">{</span>
-    <span class="k">fn</span> <span class="nf">new</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Vector</span> <span class="p">{</span>
-        <span class="k">return</span> <span class="n">Vector</span> <span class="p">{</span>
-            <span class="n">a</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span>
-            <span class="n">b</span><span class="p">:</span> <span class="n">b</span>
-        <span class="p">};</span>
-    <span class="p">}</span>
-<span class="p">}</span>
+impl Vector {
+    fn new (a: i32, b: i32) -> Vector {
+        return Vector {
+            a: a,
+            b: b
+        };
+    }
+}
 
-<span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">ops</span><span class="p">::</span><span class="nb">Add</span><span class="p">;</span>
-<span class="k">impl</span> <span class="nb">Add</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span>
-  <span class="k">type</span> <span class="n">Output</span> <span class="o">=</span> <span class="n">Vector</span><span class="p">;</span>
-  <span class="k">fn</span> <span class="nf">add</span> <span class="p">(</span><span class="k">self</span><span class="p">,</span> <span class="n">other_vector</span><span class="p">:</span> <span class="n">Vector</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Vector</span> <span class="p">{</span>
-    <span class="k">return</span> <span class="n">Vector</span> <span class="p">{</span>
-      <span class="n">a</span><span class="p">:</span> <span class="k">self</span><span class="py">.a</span> <span class="o">+</span> <span class="n">other_vector</span><span class="py">.a</span><span class="p">,</span>
-      <span class="n">b</span><span class="p">:</span> <span class="k">self</span><span class="py">.b</span> <span class="o">+</span> <span class="n">other_vector</span><span class="py">.b</span>
-    <span class="p">};</span>
-  <span class="p">}</span>
-<span class="p">}</span>
+use std::ops::Add;
+impl Add for Vector {
+  type Output = Vector;
+  fn add (self, other_vector: Vector) -> Vector {
+    return Vector {
+      a: self.a + other_vector.a,
+      b: self.b + other_vector.b
+    };
+  }
+}
 
-<span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::{</span><span class="n">Debug</span><span class="p">,</span> <span class="n">Formatter</span><span class="p">,</span> <span class="n">Result</span><span class="p">};</span>
-<span class="k">impl</span> <span class="n">Debug</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span>
-  <span class="k">fn</span> <span class="nf">fmt</span><span class="p">(</span><span class="o">&amp;</span><span class="k">self</span><span class="p">,</span> <span class="n">f</span><span class="p">:</span> <span class="o">&amp;</span><span class="k">mut</span> <span class="n">Formatter</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="n">Result</span> <span class="p">{</span>
-    <span class="k">return</span> <span class="nd">write!</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s">"Vector({}, {})"</span><span class="p">,</span> <span class="k">self</span><span class="py">.a</span><span class="p">,</span> <span class="k">self</span><span class="py">.b</span><span class="p">);</span>
-  <span class="p">}</span>
-<span class="p">}</span>
+use std::fmt::{Debug, Formatter, Result};
+impl Debug for Vector {
+  fn fmt(&self, f: &mut Formatter) -> Result {
+    return write!(f, "Vector({}, {})", self.a, self.b);
+  }
+}
 
-<span class="k">fn</span> <span class="nf">main</span> <span class="p">()</span> <span class="p">{</span>
-  <span class="k">let</span> <span class="n">v1</span> <span class="o">=</span> <span class="nn">Vector</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
-  <span class="k">let</span> <span class="n">v2</span> <span class="o">=</span> <span class="nn">Vector</span><span class="p">::</span><span class="nf">new</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">);</span>
-  <span class="k">let</span> <span class="n">v3</span> <span class="o">=</span> <span class="n">v1</span> <span class="o">+</span> <span class="n">v2</span><span class="p">;</span>
-  <span class="nd">println!</span><span class="p">(</span><span class="s">"{:?}"</span><span class="p">,</span> <span class="n">v3</span><span class="p">);</span>
-<span class="p">}</span>
-</code></pre></div></div>
+fn main () {
+  let v1 = Vector::new(1, 2);
+  let v2 = Vector::new(5, 7);
+  let v3 = v1 + v2;
+  println!("{:?}", v3);
+}
+
-<p>Oh, and you know how I said <code class="language-plaintext highlighter-rouge">{}</code> is used to communicate output to the user while <code class="language-plaintext highlighter-rouge">{:?}</code> is usually used for debugging purposes? Well, it turns out you can overload the <code class="language-plaintext highlighter-rouge">Display</code> trail (available under <code class="language-plaintext highlighter-rouge">std::fmt</code> as well) to print your object using <code class="language-plaintext highlighter-rouge">{}</code> instead of <code class="language-plaintext highlighter-rouge">{:?}</code>.</p> +

Oh, and you know how I said {} is used to communicate output to the user while {:?} is usually used for debugging purposes? Well, it turns out you can overload the Display trail (available under std::fmt as well) to print your object using {} instead of {:?}.

-<p>So, simply replace:</p> +

So, simply replace:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::{</span><span class="n">Debug</span><span class="p">,</span> <span class="n">Formatter</span><span class="p">,</span> <span class="n">Result</span><span class="p">};</span> -</code></pre></div></div> +
use std::fmt::{Debug, Formatter, Result};
+
-<p>With:</p> +

With:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">use</span> <span class="nn">std</span><span class="p">::</span><span class="nn">fmt</span><span class="p">::{</span><span class="n">Display</span><span class="p">,</span> <span class="n">Formatter</span><span class="p">,</span> <span class="n">Result</span><span class="p">};</span> -</code></pre></div></div> +
use std::fmt::{Display, Formatter, Result};
+
-<p>And:</p> +

And:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">impl</span> <span class="n">Debug</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span> -</code></pre></div></div> +
impl Debug for Vector {
+
-<p>With:</p> +

With:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">impl</span> <span class="n">Display</span> <span class="k">for</span> <span class="n">Vector</span> <span class="p">{</span> -</code></pre></div></div> +
impl Display for Vector {
+
-<p>And:</p> +

And:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">println!</span><span class="p">(</span><span class="s">"{:?}"</span><span class="p">,</span> <span class="n">v3</span><span class="p">);</span> -</code></pre></div></div> +
println!("{:?}", v3);
+
-<p>With:</p> +

With:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">println!</span><span class="p">(</span><span class="s">"{}"</span><span class="p">,</span> <span class="n">v3</span><span class="p">);</span> -</code></pre></div></div> +
println!("{}", v3);
+
-<p>And voila, you’re all set.</p> +

And voila, you’re all set.

-<h3 id="statements-vs-expressions">Statements vs. Expressions?</h3> -<p>At this point, I’m a bit tired of having to included unnecessary keywords in my code snippets, so I thought I’d introduce the concept of statement-vs-expression in Rust.</p> +

Statements vs. Expressions?

+

At this point, I’m a bit tired of having to included unnecessary keywords in my code snippets, so I thought I’d introduce the concept of statement-vs-expression in Rust.

-<p>So, basically statements that don’t end with a semi-colon (<code class="language-plaintext highlighter-rouge">;</code>) return something and they even have a special label: <code class="language-plaintext highlighter-rouge">expressions</code>. Without getting into too much detail and get you all confused, let me instead throw a little snippet at you and let you sort it out in your head.</p> +

So, basically statements that don’t end with a semi-colon (;) return something and they even have a special label: expressions. Without getting into too much detail and get you all confused, let me instead throw a little snippet at you and let you sort it out in your head.

-<p>So, let’s say you have a function that takes two <code class="language-plaintext highlighter-rouge">i32</code> arguments and returns the sum of the two values. You could have your function written like this:</p> +

So, let’s say you have a function that takes two i32 arguments and returns the sum of the two values. You could have your function written like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">sum</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i32</span> <span class="p">{</span> - <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
fn sum (a: i32, b: i32) -> i32 {
+  return a + b;
+}
+
-<p>or you could have the shorthand notation of the function by using an expression instead of a statement:</p> +

or you could have the shorthand notation of the function by using an expression instead of a statement:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">sum</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i32</span> <span class="p">{</span> - <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> -<span class="p">}</span> -</code></pre></div></div> +
fn sum (a: i32, b: i32) -> i32 {
+  a + b
+}
+
-<p>From this point on, I will be using expressions whenever possible.</p> +

From this point on, I will be using expressions whenever possible.

-<h3 id="our-journey-into-the-specifics">Our Journey into the Specifics</h3> -<p>We’re now going to dive into the basics of Rust.</p> +

Our Journey into the Specifics

+

We’re now going to dive into the basics of Rust.

-<h4 id="variableobject-declaration">Variable/Object Declaration</h4> -<p>We’ve been declaring objects and variables all over the place already, but perhaps there’s more to them than what’s been covered already. If you want to declare an integer <code class="language-plaintext highlighter-rouge">x</code> and assign the value <code class="language-plaintext highlighter-rouge">2</code> to it, you could do so as follows:</p> +

Variable/Object Declaration

+

We’ve been declaring objects and variables all over the place already, but perhaps there’s more to them than what’s been covered already. If you want to declare an integer x and assign the value 2 to it, you could do so as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> -</code></pre></div></div> +
let x = 2;
+
-<p>But if you were to write an operating system, a kernel module, and/or an application that runs on an embedded system, the size of your object really matters, and chances are you’ll need to control these sizes. Unless you dive into the specifics of the design of the compiler of Rust, you really have no idea how many bits are used to store your variable. There must be a better way to carry this out, and here’s how. Rust allows you to specify the type of your object with a slight edit to your statement. Instead of writing your variable declaration like this:</p> +

But if you were to write an operating system, a kernel module, and/or an application that runs on an embedded system, the size of your object really matters, and chances are you’ll need to control these sizes. Unless you dive into the specifics of the design of the compiler of Rust, you really have no idea how many bits are used to store your variable. There must be a better way to carry this out, and here’s how. Rust allows you to specify the type of your object with a slight edit to your statement. Instead of writing your variable declaration like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> -</code></pre></div></div> +
let x = 2;
+
-<p>You could write it like this:</p> +

You could write it like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">x</span><span class="p">:</span> <span class="nb">i8</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> -</code></pre></div></div> +
let x: i8 = 2;
+
-<p>And you know for sure that your variable is stored as an 8-bit integer.</p> +

And you know for sure that your variable is stored as an 8-bit integer.

-<p>Read more about Primitive Types and Object Declaration <a href="https://doc.Rust-lang.org/book/primitive-types.html">here</a></p> +

Read more about Primitive Types and Object Declaration here

-<h4 id="mutability">Mutability</h4> -<p>By default, objects and variables in Rust are immutable (not modifiable after they’ve been declared). Something like the following won’t work:</p> +

Mutability

+

By default, objects and variables in Rust are immutable (not modifiable after they’ve been declared). Something like the following won’t work:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">x</span><span class="p">:</span> <span class="nb">i8</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> -<span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span> -</code></pre></div></div> +
let x: i8 = 2;
+x = 3;
+
-<p>To be able to change the value of <code class="language-plaintext highlighter-rouge">x</code>, we need to tell the compiler to mark our variable as mutable (able to change value after it’s been declared). This introduces a slight change to our declaration that’s pretty intuitive; you simply add the keyword <code class="language-plaintext highlighter-rouge">mut</code> on the left side of your object declaration statement like this:</p> +

To be able to change the value of x, we need to tell the compiler to mark our variable as mutable (able to change value after it’s been declared). This introduces a slight change to our declaration that’s pretty intuitive; you simply add the keyword mut on the left side of your object declaration statement like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="k">mut</span> <span class="n">x</span><span class="p">:</span> <span class="nb">i8</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span> -</code></pre></div></div> +
let mut x: i8 = 2;
+
-<p>And now the following will work like a charm!</p> +

And now the following will work like a charm!

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">x</span> <span class="o">=</span> <span class="mi">3</span><span class="p">;</span> -</code></pre></div></div> +
x = 3;
+
-<h4 id="type-aliases">Type Aliases</h4> -<p>Rust has a keyword called <code class="language-plaintext highlighter-rouge">type</code> used to declare aliases of other types. -Say you want to use <code class="language-plaintext highlighter-rouge">i32</code> across a whole <code class="language-plaintext highlighter-rouge">class</code>, <code class="language-plaintext highlighter-rouge">module</code> or even across your whole application, and for clarity’s sake you’d rather use <code class="language-plaintext highlighter-rouge">Int</code> instead of <code class="language-plaintext highlighter-rouge">i32</code> to reference 32-bit integers. You could define your <code class="language-plaintext highlighter-rouge">Int</code> type as follows:</p> +

Type Aliases

+

Rust has a keyword called type used to declare aliases of other types. +Say you want to use i32 across a whole class, module or even across your whole application, and for clarity’s sake you’d rather use Int instead of i32 to reference 32-bit integers. You could define your Int type as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">type</span> <span class="n">Int</span> <span class="o">=</span> <span class="nb">i32</span><span class="p">;</span> -</code></pre></div></div> +
type Int = i32;
+
-<p>And now to use your new type, you could define your variables like this:</p> +

And now to use your new type, you could define your variables like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">var1</span><span class="p">:</span> <span class="n">Int</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span> -<span class="k">let</span> <span class="n">var2</span><span class="p">:</span> <span class="n">Int</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span> -</code></pre></div></div> +
let var1: Int = 10;
+let var2: Int = 20;
+
-<p>And so on.</p> +

And so on.

-<h4 id="functions">Functions</h4> -<p>Function declarations are pretty intuitive and straightforward. Say you want to write a <code class="language-plaintext highlighter-rouge">greeting</code> function that prints out the test <code class="language-plaintext highlighter-rouge">"hello there!"</code> over <code class="language-plaintext highlighter-rouge">stdio</code>. You’d write your function as follows:</p> +

Functions

+

Function declarations are pretty intuitive and straightforward. Say you want to write a greeting function that prints out the test "hello there!" over stdio. You’d write your function as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">greeting</span> <span class="p">()</span> <span class="p">{</span> - <span class="nd">println!</span><span class="p">(</span><span class="s">"hello there!"</span><span class="p">);</span> -<span class="p">}</span> -</code></pre></div></div> +
fn greeting () {
+    println!("hello there!");
+}
+
-<p>What if you want to pass the string to the function instead of hard-coding a specific value? Then, you’d write it like this:</p> +

What if you want to pass the string to the function instead of hard-coding a specific value? Then, you’d write it like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">greeting</span> <span class="p">(</span><span class="n">message</span><span class="p">:</span> <span class="nb">String</span><span class="p">)</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> -<span class="p">}</span> -</code></pre></div></div> +
fn greeting (message: String) {
+    // TODO: Implement me
+}
+
-<p>Multiple function arguments? Sure! Here’s how:</p> +

Multiple function arguments? Sure! Here’s how:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">greeting</span> <span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> <span class="n">message</span><span class="p">:</span> <span class="nb">String</span><span class="p">)</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> -<span class="p">}</span> -</code></pre></div></div> +
fn greeting (name: String, message: String) {
+    // TODO: Implement me
+}
+
-<p>Functions with return values? Here’s how:</p> +

Functions with return values? Here’s how:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">add</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i32</span> <span class="p">{</span> - <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> -<span class="p">}</span> -</code></pre></div></div> +
fn add (a: i32, b: i32) -> i32 {
+ a + b
+}
+
-<blockquote> - <p>i32 is a 32-bit integer type in Rust. You can read more about Rust’s support for numeric types <a href="https://doc.Rust-lang.org/book/primitive-types.html#numeric-types">here</a>.</p> -</blockquote> +
+

i32 is a 32-bit integer type in Rust. You can read more about Rust’s support for numeric types here.

+
-<p>Remember that we’re using an <code class="language-plaintext highlighter-rouge">expression</code> in the code snippet above. If you wanted to replace it with a statement <code class="language-plaintext highlighter-rouge">return a + b;</code> will do.</p> +

Remember that we’re using an expression in the code snippet above. If you wanted to replace it with a statement return a + b; will do.

-<h4 id="closures">Closures</h4> -<p>The easiest definition of a <code class="language-plaintext highlighter-rouge">closure</code> I can give is that a <code class="language-plaintext highlighter-rouge">closure</code> is a function with untyped arguments. If you were to write a function that multiplies two numbers together and return the product, you’d do so as follows:</p> +

Closures

+

The easiest definition of a closure I can give is that a closure is a function with untyped arguments. If you were to write a function that multiplies two numbers together and return the product, you’d do so as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">mul</span> <span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i32</span> <span class="p">{</span> - <span class="n">a</span> <span class="o">*</span> <span class="n">b</span> -<span class="p">}</span> -</code></pre></div></div> +
fn mul (a: i32, b: i32) -> i32 {
+	a * b
+}
+
-<p>This function can be written as a closure as follows:</p> +

This function can be written as a closure as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">mul</span> <span class="o">=</span> <span class="p">|</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">|</span> <span class="n">a</span> <span class="o">*</span> <span class="n">b</span><span class="p">;</span> -</code></pre></div></div> +
let mul = |a, b| a * b;
+
-<p>And then you can call it the exact same way you’d call a function, i.e.:</p> +

And then you can call it the exact same way you’d call a function, i.e.:

-<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>println!("{}", mul(10, 20)); -</code></pre></div></div> +
println!("{}", mul(10, 20));
+
-<p>If you, for whatever reason, want to strongly-type your closure arguments, you can do so by defining their types the same way you’d define function arguments, e.g.:</p> +

If you, for whatever reason, want to strongly-type your closure arguments, you can do so by defining their types the same way you’d define function arguments, e.g.:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">mul</span> <span class="o">=</span> <span class="p">|</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">|</span> <span class="n">a</span> <span class="o">*</span> <span class="n">b</span><span class="p">;</span> -</code></pre></div></div> +
let mul = |a: i32, b: i32| a * b;
+
-<p>And you can even strongly-type your closure return type as follows:</p> +

And you can even strongly-type your closure return type as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">mul</span> <span class="o">=</span> <span class="p">|</span><span class="n">a</span><span class="p">:</span> <span class="nb">i32</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="nb">i32</span><span class="p">|</span> <span class="k">-&gt;</span> <span class="nb">i32</span> <span class="p">{</span><span class="n">a</span> <span class="o">*</span> <span class="n">b</span><span class="p">};</span> -</code></pre></div></div> +
let mul = |a: i32, b: i32| -> i32 {a * b};
+
-<p>But that’ll require you to wrap your closure content within two curly brackets (<code class="language-plaintext highlighter-rouge">{</code> and <code class="language-plaintext highlighter-rouge">}</code>).</p> +

But that’ll require you to wrap your closure content within two curly brackets ({ and }).

-<p>You can read more about most of the cool stuff you can do with <code class="language-plaintext highlighter-rouge">closure</code>s <a href="https://doc.Rust-lang.org/book/closures.html">here</a>.</p> +

You can read more about most of the cool stuff you can do with closures here.

-<h4 id="function-pointers">Function Pointers</h4> -<p>If you’re coming from a solid background in languages like C and C++, chances are you’ve worked with function pointers a lot. You’ve probably even worked with function pointers in languages like JavaScript and Python without ever coming across the name. -At its core, a function pointer is a variable holding access to a specific memory location representing the beginning of the function. In JavaScript, if you were to have the following:</p> +

Function Pointers

+

If you’re coming from a solid background in languages like C and C++, chances are you’ve worked with function pointers a lot. You’ve probably even worked with function pointers in languages like JavaScript and Python without ever coming across the name. +At its core, a function pointer is a variable holding access to a specific memory location representing the beginning of the function. In JavaScript, if you were to have the following:

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">callee</span> <span class="p">()</span> <span class="p">{</span> - <span class="c1">// TODO: Implement me</span> -<span class="p">}</span> +
function callee () {
+  // TODO: Implement me
+}
 
-<span class="kd">function</span> <span class="nx">caller</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
-  <span class="c1">// TODO: Implement a task</span>
-  <span class="nx">callback</span><span class="p">();</span>
-<span class="p">}</span>
+function caller (callback) {
+  // TODO: Implement a task
+  callback();
+}
 
-<span class="nx">caller</span><span class="p">(</span><span class="nx">callback</span><span class="p">);</span>
-</code></pre></div></div>
+caller(callback);
+
-<p>It can be said that “<code class="language-plaintext highlighter-rouge">caller</code> is a function that takes an argument of type function pointer (which in this case is our <code class="language-plaintext highlighter-rouge">callee</code> function)”.</p> +

It can be said that “caller is a function that takes an argument of type function pointer (which in this case is our callee function)”.

-<p>Rust isn’t that flexible when it comes to function pointers though. If you were to pass a function pointer to a function, the calling function needs to have a somewhat hard set on callback function specifications; your calling function needs to specify the arguments and the return type of the callee function. Let’s discuss a use case where you may want to use a function pointer.</p> +

Rust isn’t that flexible when it comes to function pointers though. If you were to pass a function pointer to a function, the calling function needs to have a somewhat hard set on callback function specifications; your calling function needs to specify the arguments and the return type of the callee function. Let’s discuss a use case where you may want to use a function pointer.

-<p>Say you’re creating a struct called <code class="language-plaintext highlighter-rouge">CommandInterface</code> that will contain two fields: (1) a command string, and (2) a function pointer pointing to the function to be executed with the specified command. Let’s start by defining the outer skeleton of our interface <code class="language-plaintext highlighter-rouge">struct</code>:</p> +

Say you’re creating a struct called CommandInterface that will contain two fields: (1) a command string, and (2) a function pointer pointing to the function to be executed with the specified command. Let’s start by defining the outer skeleton of our interface struct:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">CommandInterface</span> <span class="p">{</span> - <span class="nb">str</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> - <span class="n">exec</span><span class="p">:</span> <span class="k">fn</span><span class="p">()</span> <span class="k">-&gt;</span> <span class="nb">i8</span> -<span class="p">}</span> -</code></pre></div></div> +
struct CommandInterface {
+	str: String,
+	exec: fn() -> i8
+}
+
-<p>Here we’re telling the compiler to expect our function pointer to have no arguments and return an 8-bit integer. Let’s now define a function according to these specifications:</p> +

Here we’re telling the compiler to expect our function pointer to have no arguments and return an 8-bit integer. Let’s now define a function according to these specifications:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">ls</span> <span class="p">()</span> <span class="k">-&gt;</span> <span class="nb">i8</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> - <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
fn ls () -> i8 {
+	// TODO: Implement me
+	return 0;
+}
+
-<blockquote> - <p>Our function needs not have a specific name. I’m only naming it after the command you’re about to see below to maintain a convention.</p> -</blockquote> +
+

Our function needs not have a specific name. I’m only naming it after the command you’re about to see below to maintain a convention.

+
-<p>Let’s now define our function, set the function pointer, and see how we could use the function pointer in calling our function.</p> +

Let’s now define our function, set the function pointer, and see how we could use the function pointer in calling our function.

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">cmd</span> <span class="o">=</span> <span class="n">CommandInterface</span> <span class="p">{</span> - <span class="nb">str</span><span class="p">:</span> <span class="s">"ls"</span><span class="nf">.to_string</span><span class="p">(),</span> - <span class="n">exec</span><span class="p">:</span> <span class="n">ls</span> <span class="c">// points to the ls function declared above</span> -<span class="p">};</span> +
let cmd = CommandInterface {
+	str: "ls".to_string(),
+	exec: ls // points to the ls function declared above
+};
 
-<span class="p">(</span><span class="n">cmd</span><span class="py">.exec</span><span class="p">)();</span>
-</code></pre></div></div>
+(cmd.exec)();
+
-<blockquote> - <p>The parenthesis (<code class="language-plaintext highlighter-rouge">()</code>) around <code class="language-plaintext highlighter-rouge">cmd.exec</code> are a syntax requirement. If you forget to add them, the compiler will throw an error at you.</p> -</blockquote> +
+

The parenthesis (()) around cmd.exec are a syntax requirement. If you forget to add them, the compiler will throw an error at you.

+
-<p>But what about functions with arguments? Say we want to pass some command arguments to our function, how would we do that? Well, this is pretty easy and it’ll require very slight changes. You could replace:</p> +

But what about functions with arguments? Say we want to pass some command arguments to our function, how would we do that? Well, this is pretty easy and it’ll require very slight changes. You could replace:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">exec</span><span class="p">:</span> <span class="k">fn</span><span class="p">()</span> <span class="k">-&gt;</span> <span class="nb">i8</span> -</code></pre></div></div> +
exec: fn() -> i8
+
-<p>with:</p> +

with:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">exec</span><span class="p">:</span> <span class="k">fn</span><span class="p">(</span><span class="n">arg1</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> <span class="n">arg2</span><span class="p">:</span> <span class="nb">String</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i8</span> -</code></pre></div></div> +
exec: fn(arg1: String, arg2: String) -> i8
+
-<p>and:</p> +

and:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">fn</span> <span class="nf">ls</span> <span class="p">(</span><span class="n">arg1</span><span class="p">:</span> <span class="nb">String</span><span class="p">,</span> <span class="n">arg2</span><span class="p">:</span> <span class="nb">String</span><span class="p">)</span> <span class="k">-&gt;</span> <span class="nb">i8</span> -</code></pre></div></div> +
fn ls (arg1: String, arg2: String) -> i8
+
-<p>with:</p> +

with:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="n">cmd</span><span class="py">.exec</span><span class="p">)();</span> -</code></pre></div></div> +
(cmd.exec)();
+
-<p>with something like this:</p> +

with something like this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="n">cmd</span><span class="py">.exec</span><span class="p">)(</span><span class="s">"-a"</span><span class="nf">.to_string</span><span class="p">(),</span> <span class="s">"-l"</span><span class="nf">.to_string</span><span class="p">());</span> -</code></pre></div></div> +
(cmd.exec)("-a".to_string(), "-l".to_string());
+
-<blockquote> - <p>In a practical world, it’d be better to pass a vector of arguments but I intentionally ignored vectors just to keep things clean.</p> -</blockquote> +
+

In a practical world, it’d be better to pass a vector of arguments but I intentionally ignored vectors just to keep things clean.

+
-<h4 id="conditionals">Conditionals</h4> -<p>When it comes to code path redirection, Rust has the three keywords you’ll likely find in most programming languages out there: <code class="language-plaintext highlighter-rouge">if</code>, <code class="language-plaintext highlighter-rouge">else</code>, and <code class="language-plaintext highlighter-rouge">else if</code>. If you’ve worked with languages like <code class="language-plaintext highlighter-rouge">C</code>, <code class="language-plaintext highlighter-rouge">C++</code>, <code class="language-plaintext highlighter-rouge">C#</code>, <code class="language-plaintext highlighter-rouge">Java</code>, and <code class="language-plaintext highlighter-rouge">JavaScript</code>, then you already know how to work with conditional expressions in Rust. Here’s the trick: conditional expressions in Rust are done exactly the way they’re done in the languages I just mentioned, except without the wrapping parenthesis, e.g.:</p> +

Conditionals

+

When it comes to code path redirection, Rust has the three keywords you’ll likely find in most programming languages out there: if, else, and else if. If you’ve worked with languages like C, C++, C#, Java, and JavaScript, then you already know how to work with conditional expressions in Rust. Here’s the trick: conditional expressions in Rust are done exactly the way they’re done in the languages I just mentioned, except without the wrapping parenthesis, e.g.:

-<p>The following JavaScript code:</p> +

The following JavaScript code:

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="nx">x</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">||</span> <span class="nx">x</span> <span class="o">==</span> <span class="mi">2</span><span class="p">)</span> <span class="p">{</span> - <span class="c1">// TODO: Implement me</span> -<span class="p">}</span> -<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="nx">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span> - <span class="c1">// TODO: Implement me</span> -<span class="p">}</span> -<span class="k">else</span> <span class="p">{</span> - <span class="c1">// TODO: Implement me</span> -<span class="p">}</span> -</code></pre></div></div> +
if (x == 0 || x == 2) {
+	// TODO: Implement me
+}
+else if (x == 1) {
+	// TODO: Implement me
+}
+else {
+	// TODO: Implement me
+}
+
-<p>is written in Rust as follows:</p> +

is written in Rust as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">||</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">2</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> -<span class="p">}</span> -<span class="k">else</span> <span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> -<span class="p">}</span> -<span class="k">else</span> <span class="p">{</span> - <span class="c">// TODO: Implement me</span> -<span class="p">}</span> -</code></pre></div></div> +
if x == 0 || x == 2 {
+	// TODO: Implement me
+}
+else if x == 1 {
+	// TODO: Implement me
+}
+else {
+	// TODO: Implement me
+}
+
-<p>And that’s really all there is to it when it comes to code path redirection.</p> +

And that’s really all there is to it when it comes to code path redirection.

-<p>You might, however, be used to using the <code class="language-plaintext highlighter-rouge">?</code> operator for quick things like “if <code class="language-plaintext highlighter-rouge">x</code> is even do this and if <code class="language-plaintext highlighter-rouge">x</code> is odd do that”, e.g.:</p> +

You might, however, be used to using the ? operator for quick things like “if x is even do this and if x is odd do that”, e.g.:

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// The following JavaScript statement sets `res` to 'even' if `x` is an even value, and 'odd' if `x` is an odd value</span> +
// The following JavaScript statement sets `res` to 'even' if `x` is an even value, and 'odd' if `x` is an odd value
 
-<span class="kd">var</span> <span class="nx">res</span> <span class="o">=</span> <span class="nx">x</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">?</span> <span class="dl">'</span><span class="s1">even</span><span class="dl">'</span> <span class="p">:</span> <span class="dl">'</span><span class="s1">odd</span><span class="dl">'</span><span class="p">;</span>
-</code></pre></div></div>
+var res = x % 2 == 0 ? 'even' : 'odd';
+
-<p>In Rust, the same can be written as follows:</p> +

In Rust, the same can be written as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="k">if</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">{</span><span class="s">"even"</span><span class="p">}</span> <span class="k">else</span> <span class="p">{</span><span class="s">"odd"</span><span class="p">};</span> -</code></pre></div></div> +
let res = if x % 2 == 0 {"even"} else {"odd"};
+
-<h4 id="matching-aka-pseudo-switch-case-statements">Matching (aka pseudo-Switch-Case Statements)</h4> -<p>Matching is your typical <code class="language-plaintext highlighter-rouge">switch</code> case code block plus the ability to return something. If you were to compare integer <code class="language-plaintext highlighter-rouge">x</code> against a number of different values, using classical <code class="language-plaintext highlighter-rouge">if - else -- else if</code> gets pretty tedious really quickly, so developers tend to resort to <code class="language-plaintext highlighter-rouge">switch</code> case statements. Referring back to our <code class="language-plaintext highlighter-rouge">x</code> example, the following JavaScript compares <code class="language-plaintext highlighter-rouge">x</code> against 5 different values (cases):</p> +

Matching (aka pseudo-Switch-Case Statements)

+

Matching is your typical switch case code block plus the ability to return something. If you were to compare integer x against a number of different values, using classical if - else -- else if gets pretty tedious really quickly, so developers tend to resort to switch case statements. Referring back to our x example, the following JavaScript compares x against 5 different values (cases):

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">switch</span> <span class="p">(</span><span class="nx">x</span><span class="p">)</span> <span class="p">{</span> - <span class="k">case</span> <span class="mi">1</span><span class="p">:</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">x is 1</span><span class="dl">'</span><span class="p">);</span> - <span class="k">break</span><span class="p">;</span> - <span class="k">case</span> <span class="mi">2</span><span class="p">:</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">x is 2</span><span class="dl">'</span><span class="p">);</span> - <span class="k">break</span><span class="p">;</span> - <span class="k">case</span> <span class="mi">3</span><span class="p">:</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">x is 3</span><span class="dl">'</span><span class="p">);</span> - <span class="k">break</span><span class="p">;</span> - <span class="k">case</span> <span class="mi">4</span><span class="p">:</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">x is 4</span><span class="dl">'</span><span class="p">);</span> - <span class="k">break</span><span class="p">;</span> - <span class="nl">default</span><span class="p">:</span> - <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">'</span><span class="s1">x is something else</span><span class="dl">'</span><span class="p">);</span> - <span class="k">break</span><span class="p">;</span> -<span class="p">}</span> -</code></pre></div></div> +
switch (x) {
+  case 1:
+    console.log('x is 1');
+    break;
+  case 2:
+    console.log('x is 2');
+    break;
+  case 3:
+    console.log('x is 3');
+    break;
+  case 4:
+    console.log('x is 4');
+    break;
+  default:
+    console.log('x is something else');
+    break;
+}
+
-<p>The snipper above can be written in Rust as follows:</p> +

The snipper above can be written in Rust as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">match</span> <span class="n">x</span> <span class="p">{</span> - <span class="mi">1</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is 1"</span><span class="p">),</span> - <span class="mi">2</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is 2"</span><span class="p">),</span> - <span class="mi">3</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is 3"</span><span class="p">),</span> - <span class="mi">4</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is 4"</span><span class="p">),</span> - <span class="mi">5</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is 5"</span><span class="p">),</span> - <span class="mi">_</span> <span class="k">=&gt;</span> <span class="nd">println!</span><span class="p">(</span><span class="s">"x is something else"</span><span class="p">)</span> - <span class="p">};</span> -</code></pre></div></div> +
match x {
+    1 => println!("x is 1"),
+    2 => println!("x is 2"),
+    3 => println!("x is 3"),
+    4 => println!("x is 4"),
+    5 => println!("x is 5"),
+    _ => println!("x is something else")
+  };
+
-<blockquote> - <p>_ is how you handle <code class="language-plaintext highlighter-rouge">default</code> cases</p> -</blockquote> +
+

_ is how you handle default cases

+
-<p>But things don’t end here; there’s more to <code class="language-plaintext highlighter-rouge">match</code> statements. Like I mentioned above, you can actually return a value or an object from a <code class="language-plaintext highlighter-rouge">match</code> statement. Let’s do some refactoring to our code snippet above and make it return the actual string instead of printing it to screen:</p> +

But things don’t end here; there’s more to match statements. Like I mentioned above, you can actually return a value or an object from a match statement. Let’s do some refactoring to our code snippet above and make it return the actual string instead of printing it to screen:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">res</span> <span class="o">=</span> <span class="k">match</span> <span class="n">x</span> <span class="p">{</span> - <span class="mi">1</span> <span class="k">=&gt;</span> <span class="s">"x is 1"</span><span class="p">,</span> - <span class="mi">2</span> <span class="k">=&gt;</span> <span class="s">"x is 2"</span><span class="p">,</span> - <span class="mi">3</span> <span class="k">=&gt;</span> <span class="s">"x is 3"</span><span class="p">,</span> - <span class="mi">4</span> <span class="k">=&gt;</span> <span class="s">"x is 4"</span><span class="p">,</span> - <span class="mi">5</span> <span class="k">=&gt;</span> <span class="s">"x is 5"</span><span class="p">,</span> - <span class="mi">_</span> <span class="k">=&gt;</span> <span class="s">"x is something else"</span> - <span class="p">};</span> - <span class="nd">println!</span><span class="p">(</span><span class="s">"{}"</span><span class="p">,</span> <span class="n">res</span><span class="p">);</span> -</code></pre></div></div> - -<p>That will print the exact same thing except it handed you back the string instead of printing it, and you printed it.</p> - -<p><code class="language-plaintext highlighter-rouge">match</code> can work with sophisticated objects and patterns. Read more about it <a href="https://doc.rust-lang.org/book/match.html">here</a>.</p> - -<h4 id="loops">Loops</h4> -<p>Loops are a very interesting subject in Rust. The language currently has three approaches to any kind of iterative activity. These three approaches use three separate keywords: <code class="language-plaintext highlighter-rouge">for</code>, <code class="language-plaintext highlighter-rouge">while</code>, and <code class="language-plaintext highlighter-rouge">loop</code>.</p> - -<p>The <code class="language-plaintext highlighter-rouge">for</code> loop is used when you’ve already decided the number of times you’d like to iterate. For example, the following will loop 9 times and print the values <code class="language-plaintext highlighter-rouge">0</code> through <code class="language-plaintext highlighter-rouge">9</code>:</p> - -<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">i</span> <span class="n">in</span> <span class="mi">0</span><span class="o">..</span><span class="mi">10</span> <span class="p">{</span> - <span class="nd">println!</span><span class="p">(</span><span class="s">"{}"</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span> -<span class="p">}</span> -</code></pre></div></div> - -<p>This interprets to the following Python code:</p> - -<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span> - <span class="k">print</span><span class="p">(</span><span class="s">"%d"</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> -</code></pre></div></div> - -<p>You can also iterate over a list using a <code class="language-plaintext highlighter-rouge">for</code> loop as follows:</p> +
let res = match x {
+    1 => "x is 1",
+    2 => "x is 2",
+    3 => "x is 3",
+    4 => "x is 4",
+    5 => "x is 5",
+    _ => "x is something else"
+  };
+  println!("{}", res);
+
+ +

That will print the exact same thing except it handed you back the string instead of printing it, and you printed it.

+ +

match can work with sophisticated objects and patterns. Read more about it here.

+ +

Loops

+

Loops are a very interesting subject in Rust. The language currently has three approaches to any kind of iterative activity. These three approaches use three separate keywords: for, while, and loop.

+ +

The for loop is used when you’ve already decided the number of times you’d like to iterate. For example, the following will loop 9 times and print the values 0 through 9:

+ +
for i in 0..10 {
+    println!("{}", i);
+}
+
+ +

This interprets to the following Python code:

+ +
for i in range(0, 10):
+    print("%d" % i)
+
+ +

You can also iterate over a list using a for loop as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">i</span> <span class="n">in</span> <span class="o">&amp;</span><span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">]</span> <span class="p">{</span> - <span class="nd">println!</span><span class="p">(</span><span class="s">"{}"</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span> -<span class="p">}</span> -</code></pre></div></div> - -<p>This is equivalent to the following Python code:</p> - -<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">]:</span> - <span class="k">print</span><span class="p">(</span><span class="s">"%d"</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span> -</code></pre></div></div> +
for i in &[10, 20, 30] {
+    println!("{}", i);
+}
+
+ +

This is equivalent to the following Python code:

+ +
for i in [10, 20, 30]:
+    print("%d" % i)
+
-<p><code class="language-plaintext highlighter-rouge">for</code> loops can also preform some sophisticated tasks. For instance, if you have the string <code class="language-plaintext highlighter-rouge">"hello\nworld\nmy\nname\nis\nFadi"</code> and you want it up split it up using the linefeed (<code class="language-plaintext highlighter-rouge">\n</code>) delimiter, you can use the <code class="language-plaintext highlighter-rouge">lines()</code> function. This function returns an enumerator containing both the substring and the line number. So something like the following:</p> +

for loops can also preform some sophisticated tasks. For instance, if you have the string "hello\nworld\nmy\nname\nis\nFadi" and you want it up split it up using the linefeed (\n) delimiter, you can use the lines() function. This function returns an enumerator containing both the substring and the line number. So something like the following:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">my_str_tokens</span> <span class="o">=</span> <span class="s">"hello</span><span class="se">\n</span><span class="s">world</span><span class="se">\n</span><span class="s">my</span><span class="se">\n</span><span class="s">name</span><span class="se">\n</span><span class="s">is</span><span class="se">\n</span><span class="s">Fadi"</span><span class="nf">.lines</span><span class="p">();</span> -<span class="k">for</span> <span class="p">(</span><span class="n">line_no</span><span class="p">,</span> <span class="n">term</span><span class="p">)</span> <span class="n">in</span> <span class="n">my_str_tokens</span><span class="nf">.enumerate</span><span class="p">()</span> <span class="p">{</span> - <span class="nd">println!</span><span class="p">(</span><span class="s">"{}: {}"</span><span class="p">,</span> <span class="n">line_no</span><span class="p">,</span> <span class="n">term</span><span class="p">);</span> -<span class="p">}</span> -</code></pre></div></div> - -<p>Results in this:</p> - -<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0: hello +
let my_str_tokens = "hello\nworld\nmy\nname\nis\nFadi".lines();
+for (line_no, term) in my_str_tokens.enumerate() {
+    println!("{}: {}", line_no, term);
+}
+
+ +

Results in this:

+ +
0: hello
 1: world
 2: my
 3: name
 4: is
 5: Fadi
-</code></pre></div></div>
+
-<p>The above example is equivalent to the following Python code:</p> +

The above example is equivalent to the following Python code:

-<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">myStrTokens</span> <span class="o">=</span> <span class="s">"hello</span><span class="se">\n</span><span class="s">world</span><span class="se">\n</span><span class="s">my</span><span class="se">\n</span><span class="s">name</span><span class="se">\n</span><span class="s">is</span><span class="se">\n</span><span class="s">Fadi"</span><span class="p">.</span><span class="n">split</span><span class="p">(</span><span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span> -<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">myStrTokens</span><span class="p">)):</span> - <span class="k">print</span><span class="p">(</span><span class="s">"%d: %s"</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">myStrTokens</span><span class="p">[</span><span class="n">i</span><span class="p">]))</span> -</code></pre></div></div> +
myStrTokens = "hello\nworld\nmy\nname\nis\nFadi".split("\n")
+for i in range(0, len(myStrTokens)):
+    print("%d: %s" % (i, myStrTokens[i]))
+
-<p>The <code class="language-plaintext highlighter-rouge">while</code> loop is used when you’re not sure how many times you need to loop. It works the exact same way a <code class="language-plaintext highlighter-rouge">while</code> loop works in languages like C, C++, C#, Java, JavaScript, and Python. Here’s a JavaScript example:</p> +

The while loop is used when you’re not sure how many times you need to loop. It works the exact same way a while loop works in languages like C, C++, C#, Java, JavaScript, and Python. Here’s a JavaScript example:

-<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">bool</span> <span class="nx">status</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span> -<span class="k">while</span> <span class="p">(</span><span class="nx">status</span><span class="p">)</span> <span class="p">{</span> - <span class="c1">// add some case that can set `status` to false</span> -<span class="p">}</span> -</code></pre></div></div> +
bool status = true;
+while (status) {
+  // add some case that can set `status` to false
+}
+
-<p>The snippet above can be translated into Rust and look like the following:</p> +

The snippet above can be translated into Rust and look like the following:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">status</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span> -<span class="k">while</span> <span class="n">status</span> <span class="p">{</span> - <span class="c">// add some case that can set `status` to false</span> -<span class="p">}</span> -</code></pre></div></div> +
let status: bool = true;
+while status {
+  // add some case that can set `status` to false
+}
+
-<p>The <code class="language-plaintext highlighter-rouge">loop</code> loop is used when you want to run your loop indefinitely until a terminating statement is reached. An example of when this would come in handy is when you have a web server with request handlers each assigned a thread. In a case like this you wouldn’t want to have this:</p> +

The loop loop is used when you want to run your loop indefinitely until a terminating statement is reached. An example of when this would come in handy is when you have a web server with request handlers each assigned a thread. In a case like this you wouldn’t want to have this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> <span class="n">status</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span> +
let status: bool = true;
 
-<span class="k">while</span> <span class="k">true</span> <span class="p">{</span>
-  <span class="c">// add some case that can set `status` to false</span>
-<span class="p">}</span>
-</code></pre></div></div>
+while true {
+  // add some case that can set `status` to false
+}
+
-<p>When you could actually have this:</p> +

When you could actually have this:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">loop</span> <span class="p">{</span> - <span class="c">// add some case that can break out of the loop</span> -<span class="p">}</span> -</code></pre></div></div> +
loop {
+  // add some case that can break out of the loop
+}
+
-<blockquote> - <p>“Rust’s control-flow analysis treats this construct differently than a while true, since we know that it will always loop. In general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely” - Quoted from https://doc.rust-lang.org/book/loops.html</p> -</blockquote> +
+

“Rust’s control-flow analysis treats this construct differently than a while true, since we know that it will always loop. In general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely” - Quoted from https://doc.rust-lang.org/book/loops.html

+
-<p>Here’s one more thing you’d probably like about loops in Rust. Loops can have labels. Labels are extremely useful when working with nested loops. Here’s a JavaScript example:</p> +

Here’s one more thing you’d probably like about loops in Rust. Loops can have labels. Labels are extremely useful when working with nested loops. Here’s a JavaScript example:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">var</span> <span class="n">status1</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span> -<span class="n">var</span> <span class="n">status2</span> <span class="o">=</span> <span class="k">true</span><span class="p">;</span> +
var status1 = true;
+var status2 = true;
 
-<span class="k">while</span> <span class="p">(</span><span class="n">status1</span><span class="p">)</span> <span class="p">{</span>
-  <span class="k">while</span> <span class="p">(</span><span class="n">status2</span><span class="p">)</span> <span class="p">{</span>
-    <span class="n">status1</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
-    <span class="n">status2</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span>
-  <span class="p">}</span>
-<span class="p">}</span>
-</code></pre></div></div>
+while (status1) {
+  while (status2) {
+    status1 = false;
+    status2 = false;
+  }
+}
+
-<p>The snippet above can be written with labels as follows:</p> +

The snippet above can be written with labels as follows:

-<div class="language-rust highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">'outer_loop</span><span class="p">:</span> <span class="k">loop</span> <span class="p">{</span> - <span class="nv">'inner_loop</span><span class="p">:</span> <span class="k">loop</span> <span class="p">{</span> - <span class="k">break</span> <span class="nv">'outer_loop</span><span class="p">;</span> - <span class="p">}</span> -<span class="p">}</span> -</code></pre></div></div> +
'outer_loop: loop {
+  'inner_loop: loop {
+    break 'outer_loop;
+  }
+}
+
-<p>Read more about loops <a href="https://doc.rust-lang.org/book/loops.html">here</a>.</p> +

Read more about loops here.

-<p>I think I’ve covered enough in this post and will stop right here. More stuff is coming in upcoming posts though, so stay tuned.</p>
Fadi Hanna Al-KassSo you’ve been doing high-level programming all your life, and you’ve been eyeing Rust for some time now, and you’re not sure where to start (or how to start). Well, this walk-through-like post will guide you through some of the common tasks you preform in high-level languages like JavaScript, Python, or even C#.
\ No newline at end of file +

I think I’ve covered enough in this post and will stop right here. More stuff is coming in upcoming posts though, so stay tuned.

]]>Fadi Hanna Al-Kass \ No newline at end of file diff --git a/images/avatar.jpg b/images/avatar.jpg deleted file mode 100644 index 7448f90..0000000 Binary files a/images/avatar.jpg and /dev/null differ diff --git a/images/avatar.png b/images/avatar.png new file mode 100644 index 0000000..a8a455b Binary files /dev/null and b/images/avatar.png differ diff --git a/index.html b/index.html index ec6fed8..58e3635 100644 --- a/index.html +++ b/index.html @@ -9,12 +9,8 @@ - - + + diff --git a/projects/index.html b/projects/index.html index 3d280fd..db7dd18 100644 --- a/projects/index.html +++ b/projects/index.html @@ -9,10 +9,8 @@ - - + + diff --git a/style.css b/style.css index d3d5437..c40ba64 100644 --- a/style.css +++ b/style.css @@ -41,7 +41,7 @@ blockquote, q { blockquote:before, blockquote:after, q:before, q:after { - content: ''; + content: ""; content: none; } @@ -84,7 +84,6 @@ h1, h2, h3, h4, h5, h6 { margin: 1em 0 15px; padding: 0; } - @media screen and (max-width: 640px) { h1, h2, h3, h4, h5, h6 { line-height: 1.4; @@ -95,7 +94,6 @@ h1 { font-size: 30px; color: #111111; } - h1 a { color: inherit; } @@ -124,7 +122,6 @@ a { text-decoration: none; cursor: pointer; } - a:hover, a:active { color: black; } @@ -202,7 +199,6 @@ img { padding: 20px 0; border-bottom: 1px solid #eee; } - @media screen and (max-width: 640px) { .masthead { text-align: center; @@ -215,7 +211,6 @@ img { height: 70px; margin-right: 15px; } - @media screen and (max-width: 640px) { .site-avatar { float: none; @@ -223,7 +218,6 @@ img { margin: 0 auto; } } - .site-avatar img { border-radius: 5px; } @@ -231,7 +225,6 @@ img { .site-info { float: left; } - @media screen and (max-width: 640px) { .site-info { float: none; @@ -255,7 +248,6 @@ img { color: #fff; font-size: 16px; } - @media screen and (max-width: 640px) { .site-description { margin: 3px 0; @@ -268,7 +260,6 @@ nav { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 18px; } - @media screen and (max-width: 640px) { nav { float: none; @@ -277,7 +268,6 @@ nav { font-size: 16px; } } - nav a { margin-left: 20px; color: #fff; @@ -285,11 +275,9 @@ nav a { font-weight: 300; letter-spacing: 1px; } - nav a:hover, nav a:active { color: #333333; } - @media screen and (max-width: 640px) { nav a { margin: 0 10px; @@ -308,18 +296,16 @@ nav a:hover, nav a:active { } .post blockquote { - margin: 1.8em .8em; + margin: 1.8em 0.8em; border-left: 2px solid #666; padding: 0.1em 1em; color: #666; font-size: 22px; font-style: italic; } - .post .comments { margin-top: 10px; } - .post .read-more { text-transform: uppercase; font-size: 15px; @@ -643,7 +629,6 @@ pre > code { text-decoration: none; cursor: pointer; } - .site-name a:hover { color: #333333; } @@ -653,7 +638,6 @@ nav a { text-decoration: none; cursor: pointer; } - nav a:hover { color: #b3b3b3; } @@ -661,7 +645,6 @@ nav a:hover { .post a { color: #111111; } - .post a:hover { color: black; } @@ -669,7 +652,6 @@ nav a:hover { .post-heading a { color: #666; } - .post-heading a:hover { color: #333333; } @@ -747,7 +729,6 @@ button.button-primary:focus { padding: 150px 0; } } - /* *empty spaces */ @@ -771,7 +752,6 @@ button.button-primary:focus { color: black; cursor: pointer; } - .svg-icon a:hover { color: black; } @@ -867,7 +847,7 @@ button.button-primary:focus { } .ch-img-1 { - background-image: url(/images/avatar.jpg); + background-image: url(/images/avatar.png); } .ch-info h3 { diff --git a/style.css.map b/style.css.map index c02c51c..f98ba92 100644 --- a/style.css.map +++ b/style.css.map @@ -1,20 +1 @@ -{ - "version": 3, - "file": "style.css", - "sources": [ - "style.scss", - "_sass/_reset.scss", - "_sass/_variables.scss", - "_sass/_highlights.scss", - "_sass/_jekyll-mono.scss" - ], - "sourcesContent": [ - "//\n// IMPORTS\n//\n\n@import \"reset\";\n@import \"variables\";\n\n\n/**************/\n/* BASE RULES */\n/**************/\n\nhtml {\n font-size: 100%;\n}\n\nbody {\n background: $white;\n font: 18px/1.4 $helvetica;\n color: $darkGray;\n}\n\n.container {\n margin: 0 auto;\n max-width: 740px;\n padding: 0 10px;\n width: 100%;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: $helveticaNeue;\n color: $darkerGray;\n font-weight: bold;\n\n line-height: 1.7;\n margin: 1em 0 15px;\n padding: 0;\n\n @include mobile {\n line-height: 1.4;\n }\n}\n\nh1 {\n font-size: 30px;\n color: $h1-color;\n a {\n color: inherit;\n }\n}\n\nh2 {\n font-size: 24px;\n color: $h2-color;\n}\n\nh3 {\n font-size: 20px;\n color: $h3-color;\n}\n\nh4 {\n font-size: 18px;\n color: $h4-color;\n}\n\np {\n margin: 15px 0;\n}\n\na {\n color: $link-color;\n text-decoration: none;\n\tcursor: pointer;\n &:hover, &:active {\n color: darken($link-color,20);\n }\n}\n\nul, ol {\n margin: 15px 0;\n padding-left: 30px;\n}\n\nul {\n list-style-type: disc;\n}\n\nol {\n list-style-type: decimal;\n}\n\nol ul, ul ol, ul ul, ol ol {\n margin: 0;\n}\n\nul ul, ol ul {\n list-style-type: circle;\n}\n\nem, i {\n font-style: italic;\n}\n\nstrong, b {\n font-weight: bold;\n}\n\nimg {\n max-width: 100%;\n}\n\n// Fixes images in popup boxes from Google Translate\n.gmnoprint img {\n max-width: none;\n}\n\n.date {\n font-style: italic;\n color: $gray;\n}\n\n// Specify the color of the selection\n::-moz-selection {\n color: $black;\n background: $lightGray;\n}\n::selection {\n color: $black;\n background: $lightGray;\n}\n\n.clearfix:before,\n.clearfix:after {\n content: \" \";\n display: table;\n}\n\n.clearfix:after {\n clear: both;\n}\n\n/*********************/\n/* LAYOUT / SECTIONS */\n/*********************/\n\n//\n// .masthead\n//\n\n.wrapper-masthead {\n margin-bottom: 50px;\n}\n\n.masthead {\n padding: 20px 0;\n border-bottom: 1px solid $lightGray;\n\n @include mobile {\n text-align: center;\n }\n}\n\n.site-avatar {\n float: left;\n width: 70px;\n height: 70px;\n margin-right: 15px;\n\n @include mobile {\n float: none;\n display: block;\n margin: 0 auto;\n }\n\n img {\n border-radius: 5px;\n }\n}\n\n.site-info {\n float: left;\n\n @include mobile {\n float: none;\n display: block;\n margin: 0 auto;\n }\n}\n\n.site-name {\n margin: 0;\n color: $darkGray;\n cursor: pointer;\n font-family: $helveticaNeue;\n font-weight: 300;\n font-size: 28px;\n letter-spacing: 1px;\n}\n\n.site-description {\n margin: -5px 0 0 0;\n color: $white;\n font-size: 16px;\n\n @include mobile {\n margin: 3px 0;\n }\n}\n\nnav {\n float: right;\n margin-top: 23px; \n font-family: $helveticaNeue;\n font-size: 18px;\n\n @include mobile {\n float: none;\n margin-top: 9px;\n display: block;\n font-size: 16px;\n }\n\n a {\n margin-left: 20px;\n color: $white;\n text-align: right;\n font-weight: 300;\n letter-spacing: 1px;\n \n &:hover, &:active {\n color: darken($navbar-hover-color,20);\n }\n\n @include mobile {\n margin: 0 10px;\n color: $white;\n }\n }\n}\n\n//\n// .main\n//\n\n.posts > .post {\n padding-bottom: 2em;\n border-bottom: 1px solid $lightGray;\n}\n\n.posts > .post:last-child {\n padding-bottom: 1em;\n border-bottom: none;\n}\n\n.post {\n blockquote {\n margin: 1.8em .8em;\n border-left: 2px solid $gray;\n padding: 0.1em 1em;\n color: $gray;\n font-size: 22px;\n font-style: italic;\n }\n\n .comments {\n margin-top: 10px;\n }\n\n .read-more {\n text-transform: uppercase;\n font-size: 15px;\n }\n}\n\n.wrapper-footer {\n margin-top: 50px;\n border-top: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\n background-color: $lightGray;\n}\n\nfooter {\n padding: 20px 0;\n text-align: center;\n}\n\n@import \"highlights\";\n@import \"jekyll-mono\";", - "\n/***************/\n/* MEYER RESET */\n/***************/\n\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, u, i, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed,\nfigure, figcaption, footer, header, hgroup,\nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\tfont-size: 100%;\n\tfont: inherit;\n\tvertical-align: baseline;\n}\n// HTML5 display-role reset for older browsers\narticle, aside, details, figcaption, figure,\nfooter, header, hgroup, menu, nav, section {\n\tdisplay: block;\n}\nbody {\n\tline-height: 1;\n}\nol, ul {\n\tlist-style: none;\n}\nblockquote, q {\n\tquotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n\tcontent: '';\n\tcontent: none;\n}\ntable {\n\tborder-collapse: collapse;\n\tborder-spacing: 0;\n}\n\n*, *:before, *:after {\n -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;\n}\n", - "\n//\n// VARIABLES\n//\n\n\n// Colors\n\n$black: #111111;\n$darkerGray: #222;\n$darkGray: #333;\n$gray: #666;\n$lightGray: #eee;\n$white: #fff;\n$blue: #4183C4;\n\n\n// Main theme colors\n// Some cool main theme colors(violet:#8476ad;blue:#5cacee;red:#ff7373,#ff6f69;green:#6acf64,#2ddbb3;orange:#ffa268)\n\n$mono-color:$black; // main theme color(header, links, footer icons, buttons, post-title)\n$hl-color: $gray; // header link color (author name and posted on date) for blog post meta\n$navbar-hover-color:$gray; // navbar hover color (site name and navbar links hover color)\n$link-color: $darkerGray; // normal hyperlink color other than the ones above.\n\n\n// Heading colors\n// You can play around with these too!\n$h1-color: $mono-color;\n$h2-color: $mono-color;\n$h3-color: $darkerGray;\n$h4-color: $gray;\n\n// Your avatar\n\n$avatar: \"/images/avatar.jpg\";\n\n\n// Font stacks\n$helvetica: Helvetica, Arial, sans-serif;\n$helveticaNeue: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n$raleway: \"Raleway\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n$georgia: Georgia, serif;\n\n// Mobile breakpoints\n@mixin mobile {\n @media screen and (max-width: 640px) {\n @content;\n }\n}\n", - "/**\n * Code formatting\n */\n\npre,\ncode {\n font-size: 15px;\n border: 1px solid #e8e8e8;\n border-radius: 3px;\n background-color: #292d3e;\n color: #fff;\n}\ncode {\n padding: 1px 5px;\n}\npre {\n padding: 8px 12px;\n overflow-x: auto;\n}\npre > code {\n border: 0;\n padding-right: 0;\n padding-left: 0;\n font-family: \"Ubuntu Mono\", monospace;\n}\n.highlight {\n background: #292d3e;\n box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);\n border: 0;\n padding: 15px 25px;\n tab-size: 4;\n}\n.highlight .c {\n color: #676e95;\n font-style: italic;\n}\n.highlight .err {\n color: #a2aace;\n background-color: #292d3e;\n}\n.highlight .k {\n color: #f48fb1;\n}\n.highlight .o {\n color: #a2aace;\n}\n.highlight .cm {\n color: #998;\n font-style: italic;\n}\n.highlight .cp {\n color: #b8c1ef;\n font-weight: bold;\n}\n.highlight .c1 {\n color: #626a8a;\n font-style: italic;\n}\n.highlight .cs {\n color: #999;\n font-weight: bold;\n font-style: italic;\n}\n.highlight .gd {\n color: #000;\n background-color: #fdd;\n}\n.highlight .gd .x {\n color: #000;\n background-color: #faa;\n}\n.highlight .ge {\n font-style: italic;\n}\n.highlight .gr {\n color: #a00;\n}\n.highlight .gh {\n color: #999;\n}\n.highlight .gi {\n color: #000;\n background-color: #dfd;\n}\n.highlight .gi .x {\n color: #000;\n background-color: #afa;\n}\n.highlight .go {\n color: #888;\n}\n.highlight .gp {\n color: #555;\n}\n.highlight .gs {\n font-weight: bold;\n}\n.highlight .gu {\n color: #aaa;\n}\n.highlight .gt {\n color: #a00;\n}\n.highlight .kc {\n font-weight: bold;\n}\n.highlight .kd {\n /* font-weight: bold; */\n\n color: #ba89dc;\n}\n.highlight .kp {\n font-weight: bold;\n}\n.highlight .kr {\n font-weight: bold;\n}\n.highlight .kt {\n color: #c2f3c2;\n font-weight: bold;\n}\n.highlight .m {\n color: #099;\n}\n.highlight .s {\n color: #c3e88d;\n}\n.highlight .na {\n color: #b39ddb;\n}\n.highlight .nb {\n color: #80cbc4;\n}\n.highlight .nc {\n color: #ff9800;\n font-weight: bold;\n}\n.highlight .no {\n color: #008080;\n}\n.highlight .ni {\n color: #800080;\n}\n.highlight .ne {\n color: #ffcdd2;\n font-weight: bold;\n}\n.highlight .nf {\n color: #82aaff;\n}\n.highlight .nn {\n color: #f8bbd0;\n}\n.highlight .nt {\n color: #000080;\n}\n.highlight .nv {\n color: #008080;\n}\n.highlight .ow {\n font-weight: bold;\n}\n.highlight .w {\n color: #bbb;\n}\n.highlight .mf {\n color: #099;\n}\n.highlight .mh {\n color: #099;\n}\n.highlight .mi {\n color: #00bcd4;\n}\n.highlight .mo {\n color: #099;\n}\n.highlight .sb {\n color: #00bcd4;\n}\n.highlight .sc {\n color: #00bcd4;\n}\n.highlight .sd {\n color: #00bcd4;\n}\n.highlight .s2 {\n color: #00bcd4;\n}\n.highlight .se {\n color: #00bcd4;\n}\n.highlight .sh {\n color: #00bcd4;\n}\n.highlight .si {\n color: #ffeb3b;\n}\n.highlight .sx {\n color: #00bcd4;\n}\n.highlight .sr {\n color: #009926;\n}\n.highlight .s1 {\n color: #c2e78d;\n}\n.highlight .p {\n color: #a2aace;\n}\n.highlight .ss {\n color: #00bcd4;\n}\n.highlight .bp {\n color: #cddc39;\n}\n.highlight .vc {\n color: #008080;\n}\n.highlight .vg {\n color: #008080;\n}\n.highlight .vi {\n color: #008080;\n}\n.highlight .il {\n color: #099;\n}\n.highlight .py {\n color: #ce93d8;\n}\n", - "/****************************/\n/* JEKYLL-mono-color */\n/***************************/\n\n/*\n *Title\n*/\n\n.site-name {\n a {\n color: $white;\n text-decoration: none;\n cursor: pointer;\n &:hover {\n color: darken($navbar-hover-color, 20);\n }\n }\n}\nnav {\n a {\n color: $white;\n text-decoration: none;\n cursor: pointer;\n &:hover {\n color: darken($white, 30);\n }\n }\n}\n.post {\n a {\n color: $mono-color;\n &:hover {\n color: darken($mono-color, 20);\n }\n }\n}\n\n.post-heading {\n a {\n color: $hl-color;\n &:hover {\n color: darken($hl-color, 20);\n }\n }\n}\n\n/*\n *Buttons\n*/\n\n.button,\nbutton {\n display: inline-block;\n height: 38px;\n padding: 0 30px;\n color: #555;\n text-align: center;\n font-size: 13px;\n font-weight: 600;\n line-height: 38px;\n letter-spacing: 0.1rem;\n text-decoration: none;\n white-space: nowrap;\n background-color: transparent;\n border-radius: 4px;\n border: 1px solid #bbb;\n cursor: pointer;\n box-sizing: border-box;\n}\n\n.button:hover,\nbutton:hover,\n.button:focus,\nbutton:focus {\n color: #333;\n border-color: #888;\n outline: 0;\n}\n\n.button.button-primary,\nbutton.button-primary {\n color: $mono-color;\n background-color: transparent;\n border-color: $mono-color;\n}\n\n.button.button-primary:hover,\nbutton.button-primary:hover,\n.button.button-primary:focus,\nbutton.button-primary:focus {\n color: #fff;\n background-color: $mono-color;\n border-color: $mono-color;\n}\n\n/*\n *Header\n*/\n\n.intro-header {\n border-top: 5px solid white;\n background-color: $mono-color;\n}\n\n.intro-header .post-heading {\n padding: 100px 0 50px;\n color: $white;\n}\n\n.intro-header .post-heading h1 {\n color: $white;\n font-size: 36px;\n line-height: 1.5;\n font-family: $raleway;\n}\n\n@media only screen and (min-width: 768px) {\n .intro-header .post-heading {\n padding: 150px 0;\n }\n}\n\n/*\n *empty spaces\n*/\n\n.space-medium {\n padding: 100px 0 50px;\n}\n\n.space-small {\n padding: 50px 0 25px;\n}\n\n.space-extra-small {\n padding: 30px 0 15px;\n}\n\n/*\n *svg-icons\n\n*/\n\n.svg-icon {\n a {\n color: darken($mono-color, 10);\n cursor: pointer;\n &:hover {\n color: darken($mono-color, 20);\n }\n }\n}\n\n/*\n *Image Hover Effects\n*/\n\n.centered {\n margin-left: auto;\n margin-right: auto;\n}\n\n.ch-grid {\n padding: 0;\n list-style: none;\n display: block;\n text-align: center;\n width: 100%;\n}\n\n.ch-grid:after,\n.ch-item:before {\n content: \"\";\n display: table;\n}\n\n.ch-grid:after {\n clear: both;\n}\n\n.ch-grid li {\n width: 220px;\n height: 220px;\n display: inline-block;\n}\n\n.ch-item {\n width: 100%;\n height: 100%;\n border-radius: 50%;\n position: relative;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n cursor: default;\n}\n\n.ch-info-wrap,\n.ch-info {\n position: absolute;\n width: 180px;\n height: 180px;\n border-radius: 50%;\n}\n\n.ch-info-wrap {\n top: 20px;\n left: 20px;\n background: #fff url(/images/bg.jpg);\n box-shadow: 0 0 0 20px rgba(255, 255, 255, 0.2),\n inset 0 0 3px rgba(115, 114, 23, 0.8);\n}\n\n.ch-info > div {\n display: block;\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n background-position: center center;\n -webkit-backface-visibility: hidden;\n}\n\n.ch-info .ch-info-front {\n -webkit-transition: all 0.6s ease-in-out;\n -moz-transition: all 0.6s ease-in-out;\n -o-transition: all 0.6s ease-in-out;\n -ms-transition: all 0.6s ease-in-out;\n transition: all 0.6s ease-in-out;\n}\n\n.ch-info .ch-info-back {\n opacity: 0;\n background: #fff;\n pointer-events: none;\n -webkit-transform: scale(1.5);\n -moz-transform: scale(1.5);\n -o-transform: scale(1.5);\n -ms-transform: scale(1.5);\n transform: scale(1.5);\n -webkit-transition: all 0.4s ease-in-out 0.2s;\n -moz-transition: all 0.4s ease-in-out 0.2s;\n -o-transition: all 0.4s ease-in-out 0.2s;\n -ms-transition: all 0.4s ease-in-out 0.2s;\n transition: all 0.4s ease-in-out 0.2s;\n}\n\n.ch-img-1 {\n background-image: url(#{$avatar});\n}\n\n.ch-info h3 {\n color: #000;\n text-transform: uppercase;\n letter-spacing: 2px;\n font-size: 18px;\n margin: 0 15px;\n padding: 40px 0 0 0;\n height: 80px;\n font-family: \"Open Sans\", Arial, sans-serif;\n text-shadow: 0 0 1px #fff, 0 1px 2px rgba(0, 0, 0, 0.3);\n}\n\n.ch-info p {\n color: #fff;\n padding: 10px 5px 0;\n font-style: italic;\n margin: 0 30px;\n font-size: 12px;\n}\n\n.ch-info p a {\n display: block;\n color: $mono-color;\n font-style: normal;\n font-weight: 700;\n text-transform: uppercase;\n font-size: 9px;\n letter-spacing: 1px;\n padding-top: 4px;\n font-family: \"Open Sans\", Arial, sans-serif;\n}\n\n.ch-info p a:hover {\n color: darken($mono-color, 10%);\n}\n\n.ch-item:hover .ch-info-front {\n -webkit-transform: scale(0);\n -moz-transform: scale(0);\n -o-transform: scale(0);\n -ms-transform: scale(0);\n transform: scale(0);\n opacity: 0;\n}\n\n.ch-item:hover .ch-info-back {\n -webkit-transform: scale(1);\n -moz-transform: scale(1);\n -o-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n opacity: 1;\n pointer-events: auto;\n}\n" - ], - "names": [], - "mappings": "ACCA,iBAAiB;AACjB,iBAAiB;AACjB,iBAAiB;AAEjB,AAAA,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;AAC7C,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,UAAU,EAAE,GAAG;AAC1C,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI;AAC1C,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI;AACvC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,GAAG;AACxC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM;AACf,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;AACtB,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM;AAC7B,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK;AACtC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;AAC1C,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO;AACzC,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC;EACxB,MAAM,EAAE,CAAC;EACT,OAAO,EAAE,CAAC;EACV,MAAM,EAAE,CAAC;EACT,SAAS,EAAE,IAAI;EACf,IAAI,EAAE,OAAO;EACb,cAAc,EAAE,QAAQ;CACxB;;AAED,AAAA,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM;AAC3C,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC;EAC1C,OAAO,EAAE,KAAK;CACd;;AACD,AAAA,IAAI,CAAC;EACJ,WAAW,EAAE,CAAC;CACd;;AACD,AAAA,EAAE,EAAE,EAAE,CAAC;EACN,UAAU,EAAE,IAAI;CAChB;;AACD,AAAA,UAAU,EAAE,CAAC,CAAC;EACb,MAAM,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,KAAK;AACnC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC;EACjB,OAAO,EAAE,EAAE;EACX,OAAO,EAAE,IAAI;CACb;;AACD,AAAA,KAAK,CAAC;EACL,eAAe,EAAE,QAAQ;EACzB,cAAc,EAAE,CAAC;CACjB;;AAED,AAAA,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC;EACnB,eAAe,EAAE,UAAU;EAAE,kBAAkB,EAAE,UAAU;EAAE,UAAU,EAAE,UAAU;CACpF;;AD3CD,gBAAgB;AAChB,gBAAgB;AAChB,gBAAgB;AAEhB,AAAA,IAAI,CAAC;EACH,SAAS,EAAE,IAAI;CAChB;;AAED,AAAA,IAAI,CAAC;EACH,UAAU,EEJJ,IAAI;EFKV,IAAI,EAAE,IAAI,CAAC,GAAG,CEqBJ,SAAS,EAAE,KAAK,EAAE,UAAU;EFpBtC,KAAK,EETI,IAAI;CFUd;;AAED,AAAA,UAAU,CAAC;EACT,MAAM,EAAE,MAAM;EACd,SAAS,EAAE,KAAK;EAChB,OAAO,EAAE,MAAM;EACf,KAAK,EAAE,IAAI;CACZ;;AAED,AAAA,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;EACrB,WAAW,EEUG,gBAAgB,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU;EFT5D,KAAK,EEtBM,IAAI;EFuBf,WAAW,EAAE,IAAI;EAEjB,WAAW,EAAE,GAAG;EAChB,MAAM,EAAE,UAAU;EAClB,OAAO,EAAE,CAAC;CAKX;;AEKC,MAAM,8BFjBR;EAAA,AAAA,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC;IAUnB,WAAW,EAAE,GAAG;GAEnB;CAAA;;AAED,AAAA,EAAE,CAAC;EACD,SAAS,EAAE,IAAI;EACf,KAAK,EErCC,OAAO;CFyCd;;AAND,AAGE,EAHA,CAGA,CAAC,CAAC;EACA,KAAK,EAAE,OAAO;CACf;;AAGH,AAAA,EAAE,CAAC;EACD,SAAS,EAAE,IAAI;EACf,KAAK,EE7CC,OAAO;CF8Cd;;AAED,AAAA,EAAE,CAAC;EACD,SAAS,EAAE,IAAI;EACf,KAAK,EEjDM,IAAI;CFkDhB;;AAED,AAAA,EAAE,CAAC;EACD,SAAS,EAAE,IAAI;EACf,KAAK,EEpDA,IAAI;CFqDV;;AAED,AAAA,CAAC,CAAC;EACA,MAAM,EAAE,MAAM;CACf;;AAED,AAAA,CAAC,CAAC;EACA,KAAK,EE9DM,IAAI;EF+Df,eAAe,EAAE,IAAI;EACtB,MAAM,EAAE,OAAO;CAIf;;AAPD,AAIE,CAJD,CAIG,KAAK,EAJT,CAAC,CAIY,MAAM,CAAC;EAChB,KAAK,EElEI,KAAI;CFmEd;;AAGH,AAAA,EAAE,EAAE,EAAE,CAAC;EACL,MAAM,EAAE,MAAM;EACd,YAAY,EAAE,IAAI;CACnB;;AAED,AAAA,EAAE,CAAC;EACD,eAAe,EAAE,IAAI;CACtB;;AAED,AAAA,EAAE,CAAC;EACD,eAAe,EAAE,OAAO;CACzB;;AAED,AAAA,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;EACzB,MAAM,EAAE,CAAC;CACV;;AAED,AAAA,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;EACX,eAAe,EAAE,MAAM;CACxB;;AAED,AAAA,EAAE,EAAE,CAAC,CAAC;EACJ,UAAU,EAAE,MAAM;CACnB;;AAED,AAAA,MAAM,EAAE,CAAC,CAAC;EACR,WAAW,EAAE,IAAI;CAClB;;AAED,AAAA,GAAG,CAAC;EACF,SAAS,EAAE,IAAI;CAChB;;AAGD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,SAAS,EAAE,IAAI;CAChB;;AAED,AAAA,KAAK,CAAC;EACJ,UAAU,EAAE,MAAM;EAClB,KAAK,EE5GA,IAAI;CF6GV;;EAGC,AAAF,cAAgB,CAAC;EACf,KAAK,EEpHC,OAAO;EFqHb,UAAU,EEjHA,IAAI;CFkHf;;EACC,AAAF,SAAW,CAAC;EACV,KAAK,EExHC,OAAO;EFyHb,UAAU,EErHA,IAAI;CFsHf;;AAED,AAAA,SAAS,CAAC,MAAM;AAChB,SAAS,CAAC,KAAK,CAAC;EACZ,OAAO,EAAE,GAAG;EACZ,OAAO,EAAE,KAAK;CACjB;;AAED,AAAA,SAAS,CAAC,KAAK,CAAC;EACZ,KAAK,EAAE,IAAI;CACd;;AAED,uBAAuB;AACvB,uBAAuB;AACvB,uBAAuB;AAMvB,AAAA,iBAAiB,CAAC;EAChB,aAAa,EAAE,IAAI;CACpB;;AAED,AAAA,SAAS,CAAC;EACR,OAAO,EAAE,MAAM;EACf,aAAa,EAAE,GAAG,CAAC,KAAK,CEhJd,IAAI;CFqJf;;AEnHC,MAAM,8BF4GR;EAAA,AAAA,SAAS,CAAC;IAKN,UAAU,EAAE,MAAM;GAErB;CAAA;;AAED,AAAA,YAAY,CAAC;EACX,KAAK,EAAE,IAAI;EACX,KAAK,EAAE,IAAI;EACX,MAAM,EAAE,IAAI;EACZ,YAAY,EAAE,IAAI;CAWnB;;AEpIC,MAAM,8BFqHR;EAAA,AAAA,YAAY,CAAC;IAOT,KAAK,EAAE,IAAI;IACX,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,MAAM;GAMjB;CAAA;;AAfD,AAYE,YAZU,CAYV,GAAG,CAAC;EACF,aAAa,EAAE,GAAG;CACnB;;AAGH,AAAA,UAAU,CAAC;EACT,KAAK,EAAE,IAAI;CAOZ;;AE9IC,MAAM,8BFsIR;EAAA,AAAA,UAAU,CAAC;IAIP,KAAK,EAAE,IAAI;IACX,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,MAAM;GAEjB;CAAA;;AAED,AAAA,UAAU,CAAC;EACT,MAAM,EAAE,CAAC;EACT,KAAK,EEtLI,IAAI;EFuLb,MAAM,EAAE,OAAO;EACf,WAAW,EE1JG,gBAAgB,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU;EF2J5D,WAAW,EAAE,GAAG;EAChB,SAAS,EAAE,IAAI;EACf,cAAc,EAAE,GAAG;CACpB;;AAED,AAAA,iBAAiB,CAAC;EAChB,MAAM,EAAE,UAAU;EAClB,KAAK,EE7LC,IAAI;EF8LV,SAAS,EAAE,IAAI;CAKhB;;AElKC,MAAM,8BF0JR;EAAA,AAAA,iBAAiB,CAAC;IAMd,MAAM,EAAE,KAAK;GAEhB;CAAA;;AAED,AAAA,GAAG,CAAC;EACF,KAAK,EAAE,KAAK;EACZ,UAAU,EAAE,IAAI;EAChB,WAAW,EE7KG,gBAAgB,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU;EF8K5D,SAAS,EAAE,IAAI;CAyBhB;;AEjMC,MAAM,8BFoKR;EAAA,AAAA,GAAG,CAAC;IAOA,KAAK,EAAE,IAAI;IACX,UAAU,EAAE,GAAG;IACf,OAAO,EAAE,KAAK;IACd,SAAS,EAAE,IAAI;GAmBlB;CAAA;;AA7BD,AAaE,GAbC,CAaD,CAAC,CAAC;EACA,WAAW,EAAE,IAAI;EACjB,KAAK,EEpND,IAAI;EFqNR,UAAU,EAAE,KAAK;EACjB,WAAW,EAAE,GAAG;EAChB,cAAc,EAAE,GAAG;CAUpB;;AA5BH,AAoBI,GApBD,CAaD,CAAC,CAOG,KAAK,EApBX,GAAG,CAaD,CAAC,CAOY,MAAM,CAAC;EAChB,KAAK,EE5NJ,OAAI;CF6NN;;AE1LH,MAAM,8BFiLN;EAbF,AAaE,GAbC,CAaD,CAAC,CAAC;IAYE,MAAM,EAAE,MAAM;IACd,KAAK,EE/NH,IAAI;GFiOT;CAAA;;AAOH,AAAA,MAAM,GAAG,KAAK,CAAC;EACb,cAAc,EAAE,GAAG;EACnB,aAAa,EAAE,GAAG,CAAC,KAAK,CE3Od,IAAI;CF4Of;;AAED,AAAA,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC;EACxB,cAAc,EAAE,GAAG;EACnB,aAAa,EAAE,IAAI;CACpB;;AAED,AACE,KADG,CACH,UAAU,CAAC;EACT,MAAM,EAAE,UAAU;EAClB,WAAW,EAAE,GAAG,CAAC,KAAK,CEvPnB,IAAI;EFwPP,OAAO,EAAE,SAAS;EAClB,KAAK,EEzPF,IAAI;EF0PP,SAAS,EAAE,IAAI;EACf,UAAU,EAAE,MAAM;CACnB;;AARH,AAUE,KAVG,CAUH,SAAS,CAAC;EACR,UAAU,EAAE,IAAI;CACjB;;AAZH,AAcE,KAdG,CAcH,UAAU,CAAC;EACT,cAAc,EAAE,SAAS;EACzB,SAAS,EAAE,IAAI;CAChB;;AAGH,AAAA,eAAe,CAAC;EACd,UAAU,EAAE,IAAI;EAChB,UAAU,EAAE,cAAc;EAC1B,aAAa,EAAE,cAAc;EAC7B,gBAAgB,EE3QN,IAAI;CF4Qf;;AAED,AAAA,MAAM,CAAC;EACL,OAAO,EAAE,MAAM;EACf,UAAU,EAAE,MAAM;CACnB;;AG7RD;;GAEG;AAEH,AAAA,GAAG;AACH,IAAI,CAAC;EACH,SAAS,EAAE,IAAI;EACf,MAAM,EAAE,iBAAiB;EACzB,aAAa,EAAE,GAAG;EAClB,gBAAgB,EAAE,OAAO;EACzB,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,IAAI,CAAC;EACH,OAAO,EAAE,OAAO;CACjB;;AACD,AAAA,GAAG,CAAC;EACF,OAAO,EAAE,QAAQ;EACjB,UAAU,EAAE,IAAI;CACjB;;AACD,AAAA,GAAG,GAAG,IAAI,CAAC;EACT,MAAM,EAAE,CAAC;EACT,aAAa,EAAE,CAAC;EAChB,YAAY,EAAE,CAAC;EACf,WAAW,EAAE,wBAAwB;CACtC;;AACD,AAAA,UAAU,CAAC;EACT,UAAU,EAAE,OAAO;EACnB,UAAU,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,kBAAkB;EACzC,MAAM,EAAE,CAAC;EACT,OAAO,EAAE,SAAS;EAClB,QAAQ,EAAE,CAAC;CACZ;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,OAAO;EACd,UAAU,EAAE,MAAM;CACnB;;AACD,AAAA,UAAU,CAAC,IAAI,CAAC;EACd,KAAK,EAAE,OAAO;EACd,gBAAgB,EAAE,OAAO;CAC1B;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;EACX,UAAU,EAAE,MAAM;CACnB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;EACd,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;EACd,UAAU,EAAE,MAAM;CACnB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;EACX,WAAW,EAAE,IAAI;EACjB,UAAU,EAAE,MAAM;CACnB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;EACX,gBAAgB,EAAE,IAAI;CACvB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;EAChB,KAAK,EAAE,IAAI;EACX,gBAAgB,EAAE,IAAI;CACvB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,UAAU,EAAE,MAAM;CACnB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;EACX,gBAAgB,EAAE,IAAI;CACvB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;EAChB,KAAK,EAAE,IAAI;EACX,gBAAgB,EAAE,IAAI;CACvB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,wBAAwB;EAExB,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;EACd,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;EACd,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;EACd,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,WAAW,EAAE,IAAI;CAClB;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,EAAE,CAAC;EACZ,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AACD,AAAA,UAAU,CAAC,GAAG,CAAC;EACb,KAAK,EAAE,OAAO;CACf;;ACtOD,8BAA8B;AAC9B,uBAAuB;AACvB,6BAA6B;AAE7B;;EAEE;AAEF,AACE,UADQ,CACR,CAAC,CAAC;EACA,KAAK,EFGD,IAAI;EEFR,eAAe,EAAE,IAAI;EACrB,MAAM,EAAE,OAAO;CAIhB;;AARH,AAKI,UALM,CACR,CAAC,CAIG,KAAK,CAAC;EACN,KAAK,EFHJ,OAAI;CEIN;;AAGL,AACE,GADC,CACD,CAAC,CAAC;EACA,KAAK,EFPD,IAAI;EEQR,eAAe,EAAE,IAAI;EACrB,MAAM,EAAE,OAAO;CAIhB;;AARH,AAKI,GALD,CACD,CAAC,CAIG,KAAK,CAAC;EACN,KAAK,EFXH,OAAI;CEYP;;AAGL,AACE,KADG,CACH,CAAC,CAAC;EACA,KAAK,EFtBD,OAAO;CE0BZ;;AANH,AAGI,KAHC,CACH,CAAC,CAEG,KAAK,CAAC;EACN,KAAK,EFxBH,KAAO;CEyBV;;AAIL,AACE,aADW,CACX,CAAC,CAAC;EACA,KAAK,EF5BF,IAAI;CEgCR;;AANH,AAGI,aAHS,CACX,CAAC,CAEG,KAAK,CAAC;EACN,KAAK,EF9BJ,OAAI;CE+BN;;AAIL;;EAEE;AAEF,AAAA,OAAO;AACP,MAAM,CAAC;EACL,OAAO,EAAE,YAAY;EACrB,MAAM,EAAE,IAAI;EACZ,OAAO,EAAE,MAAM;EACf,KAAK,EAAE,IAAI;EACX,UAAU,EAAE,MAAM;EAClB,SAAS,EAAE,IAAI;EACf,WAAW,EAAE,GAAG;EAChB,WAAW,EAAE,IAAI;EACjB,cAAc,EAAE,MAAM;EACtB,eAAe,EAAE,IAAI;EACrB,WAAW,EAAE,MAAM;EACnB,gBAAgB,EAAE,WAAW;EAC7B,aAAa,EAAE,GAAG;EAClB,MAAM,EAAE,cAAc;EACtB,MAAM,EAAE,OAAO;EACf,UAAU,EAAE,UAAU;CACvB;;AAED,AAAA,OAAO,CAAC,KAAK;AACb,MAAM,CAAC,KAAK;AACZ,OAAO,CAAC,KAAK;AACb,MAAM,CAAC,KAAK,CAAC;EACX,KAAK,EAAE,IAAI;EACX,YAAY,EAAE,IAAI;EAClB,OAAO,EAAE,CAAC;CACX;;AAED,AAAA,OAAO,AAAA,eAAe;AACtB,MAAM,AAAA,eAAe,CAAC;EACpB,KAAK,EFzEC,OAAO;EE0Eb,gBAAgB,EAAE,WAAW;EAC7B,YAAY,EF3EN,OAAO;CE4Ed;;AAED,AAAA,OAAO,AAAA,eAAe,CAAC,KAAK;AAC5B,MAAM,AAAA,eAAe,CAAC,KAAK;AAC3B,OAAO,AAAA,eAAe,CAAC,KAAK;AAC5B,MAAM,AAAA,eAAe,CAAC,KAAK,CAAC;EAC1B,KAAK,EAAE,IAAI;EACX,gBAAgB,EFnFV,OAAO;EEoFb,YAAY,EFpFN,OAAO;CEqFd;;AAED;;EAEE;AAEF,AAAA,aAAa,CAAC;EACZ,UAAU,EAAE,eAAe;EAC3B,gBAAgB,EF7FV,OAAO;CE8Fd;;AAED,AAAA,aAAa,CAAC,aAAa,CAAC;EAC1B,OAAO,EAAE,YAAY;EACrB,KAAK,EF7FC,IAAI;CE8FX;;AAED,AAAA,aAAa,CAAC,aAAa,CAAC,EAAE,CAAC;EAC7B,KAAK,EFjGC,IAAI;EEkGV,SAAS,EAAE,IAAI;EACf,WAAW,EAAE,GAAG;EAChB,WAAW,EFxEH,SAAS,EAAE,gBAAgB,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU;CEyElE;;AAED,MAAM,mCACJ;EAAA,AAAA,aAAa,CAAC,aAAa,CAAC;IAC1B,OAAO,EAAE,OAAO;GACjB;CAAA;;AAGH;;EAEE;AAEF,AAAA,aAAa,CAAC;EACZ,OAAO,EAAE,YAAY;CACtB;;AAED,AAAA,YAAY,CAAC;EACX,OAAO,EAAE,WAAW;CACrB;;AAED,AAAA,kBAAkB,CAAC;EACjB,OAAO,EAAE,WAAW;CACrB;;AAED;;;EAGE;AAEF,AACE,SADO,CACP,CAAC,CAAC;EACA,KAAK,EFzID,KAAO;EE0IX,MAAM,EAAE,OAAO;CAIhB;;AAPH,AAII,SAJK,CACP,CAAC,CAGG,KAAK,CAAC;EACN,KAAK,EF5IH,KAAO;CE6IV;;AAIL;;EAEE;AAEF,AAAA,SAAS,CAAC;EACR,WAAW,EAAE,IAAI;EACjB,YAAY,EAAE,IAAI;CACnB;;AAED,AAAA,QAAQ,CAAC;EACP,OAAO,EAAE,CAAC;EACV,UAAU,EAAE,IAAI;EAChB,OAAO,EAAE,KAAK;EACd,UAAU,EAAE,MAAM;EAClB,KAAK,EAAE,IAAI;CACZ;;AAED,AAAA,QAAQ,CAAC,KAAK;AACd,QAAQ,CAAC,MAAM,CAAC;EACd,OAAO,EAAE,EAAE;EACX,OAAO,EAAE,KAAK;CACf;;AAED,AAAA,QAAQ,CAAC,KAAK,CAAC;EACb,KAAK,EAAE,IAAI;CACZ;;AAED,AAAA,QAAQ,CAAC,EAAE,CAAC;EACV,KAAK,EAAE,KAAK;EACZ,MAAM,EAAE,KAAK;EACb,OAAO,EAAE,YAAY;CACtB;;AAED,AAAA,QAAQ,CAAC;EACP,KAAK,EAAE,IAAI;EACX,MAAM,EAAE,IAAI;EACZ,aAAa,EAAE,GAAG;EAClB,QAAQ,EAAE,QAAQ;EAClB,UAAU,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,kBAAkB;EACxC,MAAM,EAAE,OAAO;CAChB;;AAED,AAAA,aAAa;AACb,QAAQ,CAAC;EACP,QAAQ,EAAE,QAAQ;EAClB,KAAK,EAAE,KAAK;EACZ,MAAM,EAAE,KAAK;EACb,aAAa,EAAE,GAAG;CACnB;;AAED,AAAA,aAAa,CAAC;EACZ,GAAG,EAAE,IAAI;EACT,IAAI,EAAE,IAAI;EACV,UAAU,EAAE,IAAI,CAAC,mBAAmB;EACpC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,wBAAwB,EAC7C,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,uBAAuB;CACxC;;AAED,AAAA,QAAQ,GAAG,GAAG,CAAC;EACb,OAAO,EAAE,KAAK;EACd,QAAQ,EAAE,QAAQ;EAClB,KAAK,EAAE,IAAI;EACX,MAAM,EAAE,IAAI;EACZ,aAAa,EAAE,GAAG;EAClB,mBAAmB,EAAE,aAAa;EAClC,2BAA2B,EAAE,MAAM;CACpC;;AAED,AAAA,QAAQ,CAAC,cAAc,CAAC;EACtB,kBAAkB,EAAE,oBAAoB;EACxC,eAAe,EAAE,oBAAoB;EACrC,aAAa,EAAE,oBAAoB;EACnC,cAAc,EAAE,oBAAoB;EACpC,UAAU,EAAE,oBAAoB;CACjC;;AAED,AAAA,QAAQ,CAAC,aAAa,CAAC;EACrB,OAAO,EAAE,CAAC;EACV,UAAU,EAAE,IAAI;EAChB,cAAc,EAAE,IAAI;EACpB,iBAAiB,EAAE,UAAU;EAC7B,cAAc,EAAE,UAAU;EAC1B,YAAY,EAAE,UAAU;EACxB,aAAa,EAAE,UAAU;EACzB,SAAS,EAAE,UAAU;EACrB,kBAAkB,EAAE,yBAAyB;EAC7C,eAAe,EAAE,yBAAyB;EAC1C,aAAa,EAAE,yBAAyB;EACxC,cAAc,EAAE,yBAAyB;EACzC,UAAU,EAAE,yBAAyB;CACtC;;AAED,AAAA,SAAS,CAAC;EACR,gBAAgB,EAAE,uBAAK;CACxB;;AAED,AAAA,QAAQ,CAAC,EAAE,CAAC;EACV,KAAK,EAAE,IAAI;EACX,cAAc,EAAE,SAAS;EACzB,cAAc,EAAE,GAAG;EACnB,SAAS,EAAE,IAAI;EACf,MAAM,EAAE,MAAM;EACd,OAAO,EAAE,UAAU;EACnB,MAAM,EAAE,IAAI;EACZ,WAAW,EAAE,8BAA8B;EAC3C,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,kBAAkB;CACxD;;AAED,AAAA,QAAQ,CAAC,CAAC,CAAC;EACT,KAAK,EAAE,IAAI;EACX,OAAO,EAAE,UAAU;EACnB,UAAU,EAAE,MAAM;EAClB,MAAM,EAAE,MAAM;EACd,SAAS,EAAE,IAAI;CAChB;;AAED,AAAA,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;EACX,OAAO,EAAE,KAAK;EACd,KAAK,EFvQC,OAAO;EEwQb,UAAU,EAAE,MAAM;EAClB,WAAW,EAAE,GAAG;EAChB,cAAc,EAAE,SAAS;EACzB,SAAS,EAAE,GAAG;EACd,cAAc,EAAE,GAAG;EACnB,WAAW,EAAE,GAAG;EAChB,WAAW,EAAE,8BAA8B;CAC5C;;AAED,AAAA,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;EACjB,KAAK,EFlRC,KAAO;CEmRd;;AAED,AAAA,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC;EAC5B,iBAAiB,EAAE,QAAQ;EAC3B,cAAc,EAAE,QAAQ;EACxB,YAAY,EAAE,QAAQ;EACtB,aAAa,EAAE,QAAQ;EACvB,SAAS,EAAE,QAAQ;EACnB,OAAO,EAAE,CAAC;CACX;;AAED,AAAA,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC;EAC3B,iBAAiB,EAAE,QAAQ;EAC3B,cAAc,EAAE,QAAQ;EACxB,YAAY,EAAE,QAAQ;EACtB,aAAa,EAAE,QAAQ;EACvB,SAAS,EAAE,QAAQ;EACnB,OAAO,EAAE,CAAC;EACV,cAAc,EAAE,IAAI;CACrB" -} \ No newline at end of file +{"version":3,"sourceRoot":"","sources":["_sass/_reset.scss","style.scss","_sass/_variables.scss","_sass/_highlights.scss","_sass/_jekyll-mono.scss"],"names":[],"mappings":"AACA;AACA;AACA;AAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;EAaC;EACA;EACA;EACA;EACA;EACA;;;AAGD;AAAA;EAEC;;;AAED;EACC;;;AAED;EACC;;;AAED;EACC;;;AAED;AAAA;EAEC;EACA;;;AAED;EACC;EACA;;;AAGD;EACE;EAA6B;EAAgC;;;AC1C/D;AACA;AACA;AAEA;EACE;;;AAGF;EACE,YCJM;EDKN;EACA,OCTS;;;ADYX;EACE;EACA;EACA;EACA;;;AAGF;EACE,aCUc;EDTd,OCtBW;EDuBX;EAEA;EACA;EACA;;ACUA;EDjBF;IAUI;;;;AAIJ;EACE;EACA,OCrCM;;ADsCN;EACE;;;AAIJ;EACE;EACA,OC7CM;;;ADgDR;EACE;EACA,OCjDW;;;ADoDb;EACE;EACA,OCpDK;;;ADuDP;EACE;;;AAGF;EACE,OC9DW;ED+DX;EACD;;AACC;EACE;;;AAIJ;EACE;EACA;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAIF;EACE;;;AAGF;EACE;EACA,OC5GK;;;ADgHP;EACE,OCpHM;EDqHN,YCjHU;;;ADmHZ;EACE,OCxHM;EDyHN,YCrHU;;;ADwHZ;AAAA;EAEI;EACA;;;AAGJ;EACI;;;AAGJ;AACA;AACA;AAMA;EACE;;;AAGF;EACE;EACA;;AC9GA;ED4GF;IAKI;;;;AAIJ;EACE;EACA;EACA;EACA;;ACzHA;EDqHF;IAOI;IACA;IACA;;;AAGF;EACE;;;AAIJ;EACE;;ACvIA;EDsIF;IAII;IACA;IACA;;;;AAIJ;EACE;EACA,OCtLS;EDuLT;EACA,aC1Jc;ED2Jd;EACA;EACA;;;AAGF;EACE;EACA,OC7LM;ED8LN;;AC7JA;ED0JF;IAMI;;;;AAIJ;EACE;EACA;EACA,aC7Kc;ED8Kd;;ACxKA;EDoKF;IAOI;IACA;IACA;IACA;;;AAGF;EACE;EACA,OCpNI;EDqNJ;EACA;EACA;;AAEA;EACE;;ACzLJ;EDiLA;IAYI;IACA,OC/NE;;;;ADwOR;EACE;EACA;;;AAGF;EACE;EACA;;;AAIA;EACE;EACA;EACA;EACA,OCzPG;ED0PH;EACA;;AAGF;EACE;;AAGF;EACE;EACA;;;AAIJ;EACE;EACA;EACA;EACA,kBC3QU;;;AD8QZ;EACE;EACA;;;AE5RF;AAAA;AAAA;AAIA;AAAA;EAEE;EACA;EACA;EACA;EACA;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;EACA;EACA;;;AAEF;EACE;EACA;EACA;EACA;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;AACE;EAEA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;EACA;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;AAEF;EACE;;;ACrOF;AACA;AACA;AAEA;AAAA;AAAA;AAKE;EACE,OFGI;EEFJ;EACA;;AACA;EACE;;;AAKJ;EACE,OFPI;EEQJ;EACA;;AACA;EACE;;;AAKJ;EACE,OFtBI;;AEuBJ;EACE;;;AAMJ;EACE,OF5BG;;AE6BH;EACE;;;AAKN;AAAA;AAAA;AAIA;AAAA;EAEE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;AAAA;AAAA;AAAA;EAIE;EACA;EACA;;;AAGF;AAAA;EAEE,OFzEM;EE0EN;EACA,cF3EM;;;AE8ER;AAAA;AAAA;AAAA;EAIE;EACA,kBFnFM;EEoFN,cFpFM;;;AEuFR;AAAA;AAAA;AAIA;EACE;EACA,kBF7FM;;;AEgGR;EACE;EACA,OF7FM;;;AEgGR;EACE,OFjGM;EEkGN;EACA;EACA,aFxEQ;;;AE2EV;EACE;IACE;;;AAIJ;AAAA;AAAA;AAIA;EACE;;;AAGF;EACE;;;AAGF;EACE;;;AAGF;AAAA;;AAAA;AAME;EACE;EACA;;AACA;EACE;;;AAKN;AAAA;AAAA;AAIA;EACE;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;AAAA;EAEE;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;AAAA;EAEE;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;;;AAIF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA,OFvQM;EEwQN;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA","sourcesContent":["\n/***************/\n/* MEYER RESET */\n/***************/\n\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, u, i, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed,\nfigure, figcaption, footer, header, hgroup,\nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\tfont-size: 100%;\n\tfont: inherit;\n\tvertical-align: baseline;\n}\n// HTML5 display-role reset for older browsers\narticle, aside, details, figcaption, figure,\nfooter, header, hgroup, menu, nav, section {\n\tdisplay: block;\n}\nbody {\n\tline-height: 1;\n}\nol, ul {\n\tlist-style: none;\n}\nblockquote, q {\n\tquotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n\tcontent: '';\n\tcontent: none;\n}\ntable {\n\tborder-collapse: collapse;\n\tborder-spacing: 0;\n}\n\n*, *:before, *:after {\n -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;\n}\n","//\n// IMPORTS\n//\n\n@import \"reset\";\n@import \"variables\";\n\n\n/**************/\n/* BASE RULES */\n/**************/\n\nhtml {\n font-size: 100%;\n}\n\nbody {\n background: $white;\n font: 18px/1.4 $helvetica;\n color: $darkGray;\n}\n\n.container {\n margin: 0 auto;\n max-width: 740px;\n padding: 0 10px;\n width: 100%;\n}\n\nh1, h2, h3, h4, h5, h6 {\n font-family: $helveticaNeue;\n color: $darkerGray;\n font-weight: bold;\n\n line-height: 1.7;\n margin: 1em 0 15px;\n padding: 0;\n\n @include mobile {\n line-height: 1.4;\n }\n}\n\nh1 {\n font-size: 30px;\n color: $h1-color;\n a {\n color: inherit;\n }\n}\n\nh2 {\n font-size: 24px;\n color: $h2-color;\n}\n\nh3 {\n font-size: 20px;\n color: $h3-color;\n}\n\nh4 {\n font-size: 18px;\n color: $h4-color;\n}\n\np {\n margin: 15px 0;\n}\n\na {\n color: $link-color;\n text-decoration: none;\n\tcursor: pointer;\n &:hover, &:active {\n color: darken($link-color,20);\n }\n}\n\nul, ol {\n margin: 15px 0;\n padding-left: 30px;\n}\n\nul {\n list-style-type: disc;\n}\n\nol {\n list-style-type: decimal;\n}\n\nol ul, ul ol, ul ul, ol ol {\n margin: 0;\n}\n\nul ul, ol ul {\n list-style-type: circle;\n}\n\nem, i {\n font-style: italic;\n}\n\nstrong, b {\n font-weight: bold;\n}\n\nimg {\n max-width: 100%;\n}\n\n// Fixes images in popup boxes from Google Translate\n.gmnoprint img {\n max-width: none;\n}\n\n.date {\n font-style: italic;\n color: $gray;\n}\n\n// Specify the color of the selection\n::-moz-selection {\n color: $black;\n background: $lightGray;\n}\n::selection {\n color: $black;\n background: $lightGray;\n}\n\n.clearfix:before,\n.clearfix:after {\n content: \" \";\n display: table;\n}\n\n.clearfix:after {\n clear: both;\n}\n\n/*********************/\n/* LAYOUT / SECTIONS */\n/*********************/\n\n//\n// .masthead\n//\n\n.wrapper-masthead {\n margin-bottom: 50px;\n}\n\n.masthead {\n padding: 20px 0;\n border-bottom: 1px solid $lightGray;\n\n @include mobile {\n text-align: center;\n }\n}\n\n.site-avatar {\n float: left;\n width: 70px;\n height: 70px;\n margin-right: 15px;\n\n @include mobile {\n float: none;\n display: block;\n margin: 0 auto;\n }\n\n img {\n border-radius: 5px;\n }\n}\n\n.site-info {\n float: left;\n\n @include mobile {\n float: none;\n display: block;\n margin: 0 auto;\n }\n}\n\n.site-name {\n margin: 0;\n color: $darkGray;\n cursor: pointer;\n font-family: $helveticaNeue;\n font-weight: 300;\n font-size: 28px;\n letter-spacing: 1px;\n}\n\n.site-description {\n margin: -5px 0 0 0;\n color: $white;\n font-size: 16px;\n\n @include mobile {\n margin: 3px 0;\n }\n}\n\nnav {\n float: right;\n margin-top: 23px; \n font-family: $helveticaNeue;\n font-size: 18px;\n\n @include mobile {\n float: none;\n margin-top: 9px;\n display: block;\n font-size: 16px;\n }\n\n a {\n margin-left: 20px;\n color: $white;\n text-align: right;\n font-weight: 300;\n letter-spacing: 1px;\n \n &:hover, &:active {\n color: darken($navbar-hover-color,20);\n }\n\n @include mobile {\n margin: 0 10px;\n color: $white;\n }\n }\n}\n\n//\n// .main\n//\n\n.posts > .post {\n padding-bottom: 2em;\n border-bottom: 1px solid $lightGray;\n}\n\n.posts > .post:last-child {\n padding-bottom: 1em;\n border-bottom: none;\n}\n\n.post {\n blockquote {\n margin: 1.8em .8em;\n border-left: 2px solid $gray;\n padding: 0.1em 1em;\n color: $gray;\n font-size: 22px;\n font-style: italic;\n }\n\n .comments {\n margin-top: 10px;\n }\n\n .read-more {\n text-transform: uppercase;\n font-size: 15px;\n }\n}\n\n.wrapper-footer {\n margin-top: 50px;\n border-top: 1px solid #ddd;\n border-bottom: 1px solid #ddd;\n background-color: $lightGray;\n}\n\nfooter {\n padding: 20px 0;\n text-align: center;\n}\n\n@import \"highlights\";\n@import \"jekyll-mono\";","\n//\n// VARIABLES\n//\n\n\n// Colors\n\n$black: #111111;\n$darkerGray: #222;\n$darkGray: #333;\n$gray: #666;\n$lightGray: #eee;\n$white: #fff;\n$blue: #4183C4;\n\n\n// Main theme colors\n// Some cool main theme colors(violet:#8476ad;blue:#5cacee;red:#ff7373,#ff6f69;green:#6acf64,#2ddbb3;orange:#ffa268)\n\n$mono-color:$black; // main theme color(header, links, footer icons, buttons, post-title)\n$hl-color: $gray; // header link color (author name and posted on date) for blog post meta\n$navbar-hover-color:$gray; // navbar hover color (site name and navbar links hover color)\n$link-color: $darkerGray; // normal hyperlink color other than the ones above.\n\n\n// Heading colors\n// You can play around with these too!\n$h1-color: $mono-color;\n$h2-color: $mono-color;\n$h3-color: $darkerGray;\n$h4-color: $gray;\n\n// Your avatar\n\n$avatar: \"/images/avatar.png\";\n\n\n// Font stacks\n$helvetica: Helvetica, Arial, sans-serif;\n$helveticaNeue: \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n$raleway: \"Raleway\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n$georgia: Georgia, serif;\n\n// Mobile breakpoints\n@mixin mobile {\n @media screen and (max-width: 640px) {\n @content;\n }\n}\n","/**\n * Code formatting\n */\n\npre,\ncode {\n font-size: 15px;\n border: 1px solid #e8e8e8;\n border-radius: 3px;\n background-color: #292d3e;\n color: #fff;\n}\ncode {\n padding: 1px 5px;\n}\npre {\n padding: 8px 12px;\n overflow-x: auto;\n}\npre > code {\n border: 0;\n padding-right: 0;\n padding-left: 0;\n font-family: \"Ubuntu Mono\", monospace;\n}\n.highlight {\n background: #292d3e;\n box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);\n border: 0;\n padding: 15px 25px;\n tab-size: 4;\n}\n.highlight .c {\n color: #676e95;\n font-style: italic;\n}\n.highlight .err {\n color: #a2aace;\n background-color: #292d3e;\n}\n.highlight .k {\n color: #f48fb1;\n}\n.highlight .o {\n color: #a2aace;\n}\n.highlight .cm {\n color: #998;\n font-style: italic;\n}\n.highlight .cp {\n color: #b8c1ef;\n font-weight: bold;\n}\n.highlight .c1 {\n color: #626a8a;\n font-style: italic;\n}\n.highlight .cs {\n color: #999;\n font-weight: bold;\n font-style: italic;\n}\n.highlight .gd {\n color: #000;\n background-color: #fdd;\n}\n.highlight .gd .x {\n color: #000;\n background-color: #faa;\n}\n.highlight .ge {\n font-style: italic;\n}\n.highlight .gr {\n color: #a00;\n}\n.highlight .gh {\n color: #999;\n}\n.highlight .gi {\n color: #000;\n background-color: #dfd;\n}\n.highlight .gi .x {\n color: #000;\n background-color: #afa;\n}\n.highlight .go {\n color: #888;\n}\n.highlight .gp {\n color: #555;\n}\n.highlight .gs {\n font-weight: bold;\n}\n.highlight .gu {\n color: #aaa;\n}\n.highlight .gt {\n color: #a00;\n}\n.highlight .kc {\n font-weight: bold;\n}\n.highlight .kd {\n /* font-weight: bold; */\n\n color: #ba89dc;\n}\n.highlight .kp {\n font-weight: bold;\n}\n.highlight .kr {\n font-weight: bold;\n}\n.highlight .kt {\n color: #c2f3c2;\n font-weight: bold;\n}\n.highlight .m {\n color: #099;\n}\n.highlight .s {\n color: #c3e88d;\n}\n.highlight .na {\n color: #b39ddb;\n}\n.highlight .nb {\n color: #80cbc4;\n}\n.highlight .nc {\n color: #ff9800;\n font-weight: bold;\n}\n.highlight .no {\n color: #008080;\n}\n.highlight .ni {\n color: #800080;\n}\n.highlight .ne {\n color: #ffcdd2;\n font-weight: bold;\n}\n.highlight .nf {\n color: #82aaff;\n}\n.highlight .nn {\n color: #f8bbd0;\n}\n.highlight .nt {\n color: #000080;\n}\n.highlight .nv {\n color: #008080;\n}\n.highlight .ow {\n font-weight: bold;\n}\n.highlight .w {\n color: #bbb;\n}\n.highlight .mf {\n color: #099;\n}\n.highlight .mh {\n color: #099;\n}\n.highlight .mi {\n color: #00bcd4;\n}\n.highlight .mo {\n color: #099;\n}\n.highlight .sb {\n color: #00bcd4;\n}\n.highlight .sc {\n color: #00bcd4;\n}\n.highlight .sd {\n color: #00bcd4;\n}\n.highlight .s2 {\n color: #00bcd4;\n}\n.highlight .se {\n color: #00bcd4;\n}\n.highlight .sh {\n color: #00bcd4;\n}\n.highlight .si {\n color: #ffeb3b;\n}\n.highlight .sx {\n color: #00bcd4;\n}\n.highlight .sr {\n color: #009926;\n}\n.highlight .s1 {\n color: #c2e78d;\n}\n.highlight .p {\n color: #a2aace;\n}\n.highlight .ss {\n color: #00bcd4;\n}\n.highlight .bp {\n color: #cddc39;\n}\n.highlight .vc {\n color: #008080;\n}\n.highlight .vg {\n color: #008080;\n}\n.highlight .vi {\n color: #008080;\n}\n.highlight .il {\n color: #099;\n}\n.highlight .py {\n color: #ce93d8;\n}\n","/****************************/\n/* JEKYLL-mono-color */\n/***************************/\n\n/*\n *Title\n*/\n\n.site-name {\n a {\n color: $white;\n text-decoration: none;\n cursor: pointer;\n &:hover {\n color: darken($navbar-hover-color, 20);\n }\n }\n}\nnav {\n a {\n color: $white;\n text-decoration: none;\n cursor: pointer;\n &:hover {\n color: darken($white, 30);\n }\n }\n}\n.post {\n a {\n color: $mono-color;\n &:hover {\n color: darken($mono-color, 20);\n }\n }\n}\n\n.post-heading {\n a {\n color: $hl-color;\n &:hover {\n color: darken($hl-color, 20);\n }\n }\n}\n\n/*\n *Buttons\n*/\n\n.button,\nbutton {\n display: inline-block;\n height: 38px;\n padding: 0 30px;\n color: #555;\n text-align: center;\n font-size: 13px;\n font-weight: 600;\n line-height: 38px;\n letter-spacing: 0.1rem;\n text-decoration: none;\n white-space: nowrap;\n background-color: transparent;\n border-radius: 4px;\n border: 1px solid #bbb;\n cursor: pointer;\n box-sizing: border-box;\n}\n\n.button:hover,\nbutton:hover,\n.button:focus,\nbutton:focus {\n color: #333;\n border-color: #888;\n outline: 0;\n}\n\n.button.button-primary,\nbutton.button-primary {\n color: $mono-color;\n background-color: transparent;\n border-color: $mono-color;\n}\n\n.button.button-primary:hover,\nbutton.button-primary:hover,\n.button.button-primary:focus,\nbutton.button-primary:focus {\n color: #fff;\n background-color: $mono-color;\n border-color: $mono-color;\n}\n\n/*\n *Header\n*/\n\n.intro-header {\n border-top: 5px solid white;\n background-color: $mono-color;\n}\n\n.intro-header .post-heading {\n padding: 100px 0 50px;\n color: $white;\n}\n\n.intro-header .post-heading h1 {\n color: $white;\n font-size: 36px;\n line-height: 1.5;\n font-family: $raleway;\n}\n\n@media only screen and (min-width: 768px) {\n .intro-header .post-heading {\n padding: 150px 0;\n }\n}\n\n/*\n *empty spaces\n*/\n\n.space-medium {\n padding: 100px 0 50px;\n}\n\n.space-small {\n padding: 50px 0 25px;\n}\n\n.space-extra-small {\n padding: 30px 0 15px;\n}\n\n/*\n *svg-icons\n\n*/\n\n.svg-icon {\n a {\n color: darken($mono-color, 10);\n cursor: pointer;\n &:hover {\n color: darken($mono-color, 20);\n }\n }\n}\n\n/*\n *Image Hover Effects\n*/\n\n.centered {\n margin-left: auto;\n margin-right: auto;\n}\n\n.ch-grid {\n padding: 0;\n list-style: none;\n display: block;\n text-align: center;\n width: 100%;\n}\n\n.ch-grid:after,\n.ch-item:before {\n content: \"\";\n display: table;\n}\n\n.ch-grid:after {\n clear: both;\n}\n\n.ch-grid li {\n width: 220px;\n height: 220px;\n display: inline-block;\n}\n\n.ch-item {\n width: 100%;\n height: 100%;\n border-radius: 50%;\n position: relative;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);\n cursor: default;\n}\n\n.ch-info-wrap,\n.ch-info {\n position: absolute;\n width: 180px;\n height: 180px;\n border-radius: 50%;\n}\n\n.ch-info-wrap {\n top: 20px;\n left: 20px;\n background: #fff url(/images/bg.jpg);\n box-shadow: 0 0 0 20px rgba(255, 255, 255, 0.2),\n inset 0 0 3px rgba(115, 114, 23, 0.8);\n}\n\n.ch-info > div {\n display: block;\n position: absolute;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n background-position: center center;\n -webkit-backface-visibility: hidden;\n}\n\n.ch-info .ch-info-front {\n -webkit-transition: all 0.6s ease-in-out;\n -moz-transition: all 0.6s ease-in-out;\n -o-transition: all 0.6s ease-in-out;\n -ms-transition: all 0.6s ease-in-out;\n transition: all 0.6s ease-in-out;\n}\n\n.ch-info .ch-info-back {\n opacity: 0;\n background: #fff;\n pointer-events: none;\n -webkit-transform: scale(1.5);\n -moz-transform: scale(1.5);\n -o-transform: scale(1.5);\n -ms-transform: scale(1.5);\n transform: scale(1.5);\n -webkit-transition: all 0.4s ease-in-out 0.2s;\n -moz-transition: all 0.4s ease-in-out 0.2s;\n -o-transition: all 0.4s ease-in-out 0.2s;\n -ms-transition: all 0.4s ease-in-out 0.2s;\n transition: all 0.4s ease-in-out 0.2s;\n}\n\n.ch-img-1 {\n background-image: url(#{$avatar});\n}\n\n.ch-info h3 {\n color: #000;\n text-transform: uppercase;\n letter-spacing: 2px;\n font-size: 18px;\n margin: 0 15px;\n padding: 40px 0 0 0;\n height: 80px;\n font-family: \"Open Sans\", Arial, sans-serif;\n text-shadow: 0 0 1px #fff, 0 1px 2px rgba(0, 0, 0, 0.3);\n}\n\n.ch-info p {\n color: #fff;\n padding: 10px 5px 0;\n font-style: italic;\n margin: 0 30px;\n font-size: 12px;\n}\n\n.ch-info p a {\n display: block;\n color: $mono-color;\n font-style: normal;\n font-weight: 700;\n text-transform: uppercase;\n font-size: 9px;\n letter-spacing: 1px;\n padding-top: 4px;\n font-family: \"Open Sans\", Arial, sans-serif;\n}\n\n.ch-info p a:hover {\n color: darken($mono-color, 10%);\n}\n\n.ch-item:hover .ch-info-front {\n -webkit-transform: scale(0);\n -moz-transform: scale(0);\n -o-transform: scale(0);\n -ms-transform: scale(0);\n transform: scale(0);\n opacity: 0;\n}\n\n.ch-item:hover .ch-info-back {\n -webkit-transform: scale(1);\n -moz-transform: scale(1);\n -o-transform: scale(1);\n -ms-transform: scale(1);\n transform: scale(1);\n opacity: 1;\n pointer-events: auto;\n}\n"],"file":"style.css"} \ No newline at end of file