-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric.rs
More file actions
325 lines (276 loc) · 7.03 KB
/
Copy pathgeneric.rs
File metadata and controls
325 lines (276 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// use std::ops::{Add, Sub, Mul, Div}; // for operator overloading
#[derive(Copy, Clone)]
#[derive(Debug)] // for pretty print
//struct
struct Point{
x: i32,
y: i32,
}
// enum
enum Expr{
Null,
Add(i32, i32),
Sub(i32, i32),
Mul(i32, i32),
Div{dividend: i32, divisor: i32}, // using {} not ()
Val(i32),
}
// function
fn print_point(point: Point){
println!("x: {}, y: {}", point.x, point.y);
}
//pattern matching
fn match_expr(expr: Expr){
match expr {
Expr::Null => println!("Null"),
Expr::Add(x, y) => println!("Add: {} + {}", x, y),
Expr::Sub(x, y) => println!("Sub: {} - {}", x, y),
Expr::Mul(x, y) => println!("Mul: {} * {}", x, y),
Expr::Div{ dividend: x, divisor: y} => println!("Div: {} / {}", x, y),
Expr::Val(x) => println!("Val: {}", x),
_ => println!("Unhandle expression / case"),
}
}
fn uppercase(c: u8) -> char {
match c {
b'a'..b'z' => (c - 32) as char,
_ => c as char, // as is used to cast between types
}
}
fn is_alphanumeric(c: char) -> bool{
match c{
'a'..'z' | 'A'..'Z' | '0'..'9' => true,
_ => false,
}
}
fn uppercases(c :u8) -> u8{
if let b'a'..b'z' = c{
c - 32
} else {
c
}
}
// macros
macro_rules! int_bitset{
($ty:ty) => {
impl BitSet for $ty{
fn clear(&mut self, index: usize){
*self &= !(1 << index);
}
fn set(&mut self, index: usize){
*self |= 1 << index;
}
fn is_set(&self, index: usize) -> bool{
(*self >> index) & 1 == 1
}
fn toogle(&mut self, index: usize){
*self ^=1 << index;
}
}
};
}
macro_rules! op{
(+ $_self:ident : $self_type:ty, $other:ident $expr:expr) => {
impl ::std::ops::Add for $self_type{
type Output = $self_type;
fn add($_self, $other: $self_type) -> $self_type{
$expr
}
}
};
(- $_self:ident : $self_type:ty, $other:ident $expr:expr) => {
impl ::std::ops::Sub for $self_type{
type Output = $self_type;
fn sub($_self, $other: $self_type) -> $self_type{
$expr
}
}
};
(* $_self:ident : $self_type:ty, $other:ident $expr:expr) => {
impl ::std::ops::Mul for $self_type{
type Output = $self_type;
fn mul($_self, $other: $self_type) -> $self_type{
$expr
}
}
};
(/ $_self:ident : $self_type:ty, $other:ident $expr:expr) => {
impl ::std::ops::Div for $self_type{
type Output = $self_type;
fn div($_self, $other: $self_type) -> $self_type{
$expr
}
}
};
}
macro_rules! hash{
($ ($key:expr => $value:expr,) *) => {{ // inside coma if we want optional patterns, outside if we don't
let mut hashmap = ::std::collections::HashMap::new();
$(hashmap.insert($key, $value);)*
hashmap
}};
}
#[warn(unused_mut)]
fn main() {
let mut p1 = Point { x: 10, y: 20 };
println!("{:#?}", p1); // pretty print
let mut p2 = p1;
print_point(p1);
println!("{}", p2.x);
inc_x(&mut p2);
print_point(p2);
/*
without #[derive(Copy, Clone)]:
let p1 = Point { x: 10, y: 20 };
let p2 = p1;
ERROR, point doesn't implement copy trait and clone either
*/
// tuple
let tuple = (24, 42);
let (hello, world) = "helloworld".split_at(5);
println!("{} {}", tuple.0, tuple.1);
println!("{} {}", hello, world);
//enum
let quotient = Expr::Div{ dividend: 10, divisor: 2 };
let sum = Expr::Add(40, 2);
//traits
let mut num = 0;
num.set(5);
println!("{}", num.is_set(5)); // true
num.clear(5);
//associated types
let pp1 = Point{ x: 10, y: 20 };
let pp2 = Point{ x: 30, y: 40 };
let pp3 = pp1 + pp2; // operator overloading
println!("{:#?}", pp3); // pretty print
println!("{:#?}", pp1.dist_from_origin()); // pretty print
//macros usage
int_bitset!(i32);
int_bitset!(u8);
// int_bitset!(u64); ERROR: 67 | impl BitSet for $ty{
// | ^^^^^^^^^^^^^^^^^^^ conflicting implementation for `u64`
// that's because i declared that twice
//using other macros:
op!(+ self:Point, other{
Point{
x: self.x + other.x,
y: self.y + other.y,
}
});
op!(- self:Point, other{
Point{
x: self.x - other.x,
y: self.y - other.y,
}
});
let hashmap = hash! {
"one" => 1,
"two" => 2,
};
println!("{:#?}", hashmap)
}
//fn not implementes in type
fn inc_x(point: &mut Point){
point.x += 1;
}
// methods / implementation
impl Point{
fn dist_from_origin(&self) -> f64{
let sum_of_squares = self.x.pow(2) + self.y.pow(2); // https://doc.rust-lang.org/stable/std/primitive.i32.html#method.pow
(sum_of_squares as f64).sqrt()
}
fn translate(&mut self, dx: i32, dy: i32){
self.x += dx;
self.y += dy;
}
}
impl Point{
fn new(x: i32, y: i32) -> Self{ // used like: let point = Point::new(i32, i32);
Self { x, y }
}
}
impl Point{
fn origin() -> Self{
Point { x: 0, y: 0 }
}
}
//traits
trait BitSet{
fn clear(&mut self, index: usize);
fn set(&mut self, index: usize);
fn is_set(&self, index: usize) -> bool;
fn toogle(&mut self, index: usize){
if self.is_set(index){
self.clear(index);
} else {
self.set(index);
}
}
}
impl BitSet for u64{
fn clear(&mut self, index: usize){
*self &= !(1 << index);
}
fn set(&mut self, index: usize){
*self |= 1 << index;
}
fn is_set(&self, index: usize) -> bool{
(*self >> index) & 1 == 1
}
fn toogle(&mut self, index: usize){
*self ^=1 << index;
}
}
/*
impl Add<Point> for Point{
type Output = Point;
fn add(self, point: Point) -> Self::Output{
Point{
x: self.x + point.x,
y: self.y + point.y,
}
}
}
need to comment that because we used a macro instead of an implementation
*/
//Generics
fn max<T: PartialOrd>(a: T, b: T) -> T{
if a > b{
a
}else{
b
}
}
//slice
fn first<T>(slice: &[T]) -> &T{
if slice.is_empty(){
panic!("slice is empty")
}else{
&slice[0]
}
}
//for loops over a slice
fn index<T: PartialEq>(slice: &[T], target: &T) -> Option<usize>{
for (index, element) in slice.iter().enumerate(){
if element == target {
return Some(index);
}
}
None
}
fn min_max(slice: &[i32]) -> Option<(i32, i32)>{
if slice.is_empty(){
return None;
}
let mut min = slice[0];
let mut max = slice[0];
for &element in slice{
if element < min{
min = element;
}
if element > max{
max = element;
}
}
Some((min, max))
}