Skip to content

Instantly share code, notes, and snippets.

View eventhelix's full-sized avatar

EventHelix.com Inc. eventhelix

View GitHub Profile
@eventhelix
eventhelix / complex.rs
Last active May 14, 2022 21:13
Complex numbers
use std::rc::Rc;
use std::sync::Arc;
pub struct Complex {
real: f64,
imaginary: f64,
}
impl Complex {
pub fn magnitude_self_ownership(self) -> f64 {
@eventhelix
eventhelix / count_char.rs
Created May 14, 2022 17:04
Count characters in a string
pub fn count_char(find: char, search_str: &str) -> usize {
let mut count = 0;
for next in search_str.chars() {
if find == next {
count += 1;
}
}
count
}
example::double:
mov rax, rdi
mov rcx, qword ptr [rsi] ; Read the enum discriminator
test rcx, rcx ; Check the discriminator for 0
je .LBB0_5
cmp ecx, 1
jne .LBB0_3
movsd xmm0, qword ptr [rsi + 8]
addsd xmm0, xmm0
movsd qword ptr [rax + 8], xmm0
pub enum Number {
Integer (usize),
Real (f64),
Complex(f64, f64)
}
pub fn double (num: Number) -> Number {
match num {
Number::Integer (n) => Number::Integer(n+n),
Number::Real (n) => Number::Real (n+n),
@eventhelix
eventhelix / add.asm
Last active May 7, 2022 17:36
Code generated for a Rust function that adds two numbers
; The caller has passed a and b in rdi and rsi. The load effective address
; instruction is used (misused?) to perform the addition.
lea rax, [rdi + rsi]
ret
@eventhelix
eventhelix / add.rs
Last active May 7, 2022 17:38
A simple function in Rust
pub fn add(a: u64, b: u64) -> u64 {
a + b
}
% values outside 0-65535 Time (secs) no hint Time (secs) unlikely
.1% 8.01 6.17 (-1.84)
1% 8.25 6.76 (-1.49)
5% 9.36 7.91 (-1.45)
10% 10.83 9.42 (-1.41)
50% 22.55 23.42 (+0.87)
90% 33.91 35.42 (+1.51)
95% 34.35 35.88 (+1.53)
99% 34.48 36.02 (+1.54)
99.9% 34.53 36.03 (+1.5)
@eventhelix
eventhelix / recursive-constexpr.cpp
Last active July 18, 2021 06:02
Example of a recursive factorial function
#include <array>
#include <cstdint>
#include <cstdio>
constexpr std::uint64_t factorial(std::uint64_t n) {
// Recursion termination condition
if (n == 0)
{
return 1;
}
factorial(unsigned int):
mov eax, 1 ; The default return value eax=1
test edi, edi ; Check if the input parameter n is 0
je .L1 ; If n is 0, just return
.L2: ; Loop return variable
imul eax, edi ; eax = eax*n
sub edi, 1 ; n = n-1
jne .L2 ; Loop if n is non-zero
.L1: ; Jump label for n==0 case
ret ; Return result in eax
unsigned int factorial(unsigned int n)
{
// Recursion termination condition
if (n == 0)
{
return 1;
}
return n*factorial(n-1);
}