-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple.naml
More file actions
973 lines (836 loc) Β· 25 KB
/
simple.naml
File metadata and controls
973 lines (836 loc) Β· 25 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// =============================================================================
// Generic Collections Library
// =============================================================================
interface Comparable<T> {
fn compare(other: T) -> int;
fn equals(other: T) -> bool;
}
interface Hashable {
fn hash() -> uint;
}
interface Iterator<T> {
fn next() -> option<T>;
fn has_next() -> bool;
}
interface Iterable<T> {
fn iter() -> Iterator<T>;
}
interface Collection<T> {
fn size() -> int;
fn is_empty() -> bool;
fn contains(item: T) -> bool;
fn add(item: T);
fn remove(item: T) -> bool;
fn clear();
}
interface Serializable {
fn to_json() -> string;
fn to_bytes() -> bytes;
}
// =============================================================================
// Error Types
// =============================================================================
exception NetworkError {
message: string,
code: int,
retry_after: option<int>
}
exception ValidationError {
field: string,
message: string,
value: string
}
exception DatabaseError {
query: string,
message: string,
error_code: int
}
exception AuthenticationError {
user_id: string,
reason: string,
timestamp: int
}
// =============================================================================
// Domain Models
// =============================================================================
pub struct UserId implements Comparable<UserId>, Hashable {
pub value: string
}
pub fn (self: UserId) compare(other: UserId) -> int {
if (self.value == other.value) {
return 0;
}
if (self.value < other.value) {
return -1;
}
return 1;
}
pub fn (self: UserId) equals(other: UserId) -> bool {
return self.value == other.value;
}
pub fn (self: UserId) hash() -> uint {
var h: uint = 0;
for (i, c in self.value) {
h = h * 31 + (c as uint);
}
return h;
}
pub struct Email implements Comparable<Email> {
pub local: string,
pub domain: string
}
pub fn (self: Email) to_string() -> string {
return self.local + "@" + self.domain;
}
pub fn (self: Email) compare(other: Email) -> int {
var self_str: string = self.to_string();
var other_str: string = other.to_string();
if (self_str == other_str) {
return 0;
}
if (self_str < other_str) {
return -1;
}
return 1;
}
pub fn (self: Email) equals(other: Email) -> bool {
return self.local == other.local && self.domain == other.domain;
}
pub struct Address {
pub street: string,
pub city: string,
pub state: string,
pub zip: string,
pub country: string
}
pub fn (self: Address) format() -> string {
return self.street + "\n" + self.city + ", " + self.state + " " + self.zip + "\n" + self.country;
}
pub fn (self: Address) is_valid() -> bool {
return self.street != "" && self.city != "" && self.zip != "";
}
pub struct PhoneNumber {
pub country_code: string,
pub area_code: string,
pub number: string,
pub extension: option<string>
}
pub fn (self: PhoneNumber) format() -> string {
var base: string = "+" + self.country_code + " (" + self.area_code + ") " + self.number;
var ext: string = self.extension else {
return base;
}
return base + " ext. " + ext;
}
enum UserStatus {
Active,
Inactive,
Suspended(string),
PendingVerification(string),
Deleted(int)
}
enum UserRole {
Admin,
Moderator,
User,
Guest,
Custom(string, [string])
}
pub struct User implements Serializable {
pub id: UserId,
pub email: Email,
pub username: string,
pub password_hash: string,
pub first_name: option<string>,
pub last_name: option<string>,
pub address: option<Address>,
pub phone: option<PhoneNumber>,
pub status: UserStatus,
pub roles: [UserRole],
pub metadata: map<string, string>,
pub created_at: int,
pub updated_at: int,
pub last_login: option<int>
}
pub fn (self: User) full_name() -> string {
var first: string = self.first_name.or_default("");
var last: string = self.last_name.or_default("");
if (first == "" && last == "") {
return self.username;
}
if (first == "") {
return last;
}
if (last == "") {
return first;
}
return first + " " + last;
}
pub fn (self: User) is_active() -> bool {
switch (self.status) {
case Active: {
return true;
}
default: {
return false;
}
}
}
pub fn (self: User) has_role(role: UserRole) -> bool {
for (r in self.roles) {
if (r == role) {
return true;
}
}
return false;
}
pub fn (self: User) is_admin() -> bool {
return self.has_role(UserRole::Admin);
}
pub fn (self: User) to_json() -> string {
return "{\"id\": \"" + self.id.value + "\", \"email\": \"" + self.email.to_string() + "\"}";
}
pub fn (self: User) to_bytes() -> bytes {
return self.to_json() as bytes;
}
// =============================================================================
// Generic Data Structures
// =============================================================================
pub struct LinkedListNode<T> {
pub value: T,
pub next: option<LinkedListNode<T>>
}
pub struct LinkedList<T> implements Collection<T> {
pub head: option<LinkedListNode<T>>,
pub tail: option<LinkedListNode<T>>,
pub length: int
}
pub fn (self: LinkedList<T>) size() -> int {
return self.length;
}
pub fn (self: LinkedList<T>) is_empty() -> bool {
return self.length == 0;
}
pub fn (mut self: LinkedList<T>) add(item: T) {
var node: LinkedListNode<T> = LinkedListNode { value: item, next: none };
if (self.head.is_none()) {
self.head = some(node);
self.tail = some(node);
} else {
var tail_node: LinkedListNode<T> = self.tail else {
return;
}
tail_node.next = some(node);
self.tail = some(node);
}
self.length = self.length + 1;
}
pub fn (self: LinkedList<T>) contains(item: T) -> bool {
var current: option<LinkedListNode<T>> = self.head;
while (current.is_some()) {
var node: LinkedListNode<T> = current else {
break;
}
if (node.value == item) {
return true;
}
current = node.next;
}
return false;
}
pub fn (mut self: LinkedList<T>) remove(item: T) -> bool {
if (self.head.is_none()) {
return false;
}
var head_node: LinkedListNode<T> = self.head else {
return false;
}
if (head_node.value == item) {
self.head = head_node.next;
self.length = self.length - 1;
return true;
}
var current: option<LinkedListNode<T>> = self.head;
while (current.is_some()) {
var curr_node: LinkedListNode<T> = current else {
break;
}
if (curr_node.next.is_none()) {
break;
}
var next_node: LinkedListNode<T> = curr_node.next else {
break;
}
if (next_node.value == item) {
curr_node.next = next_node.next;
self.length = self.length - 1;
return true;
}
current = curr_node.next;
}
return false;
}
pub fn (mut self: LinkedList<T>) clear() {
self.head = none;
self.tail = none;
self.length = 0;
}
pub struct TreeNode<T> {
pub value: T,
pub left: option<TreeNode<T>>,
pub right: option<TreeNode<T>>,
pub height: int
}
pub fn (self: TreeNode<T>) is_leaf() -> bool {
return self.left.is_none() && self.right.is_none();
}
pub fn (self: TreeNode<T>) balance_factor() -> int {
var left_height: int = 0;
var right_height: int = 0;
if (self.left.is_some()) {
var left_node: TreeNode<T> = self.left else {
return 0;
}
left_height = left_node.height;
}
if (self.right.is_some()) {
var right_node: TreeNode<T> = self.right else {
return left_height;
}
right_height = right_node.height;
}
return left_height - right_height;
}
pub struct BinarySearchTree<T: Comparable<T>> {
pub root: option<TreeNode<T>>,
pub size: int
}
pub fn (mut self: BinarySearchTree<T>) insert(value: T) {
var node: TreeNode<T> = TreeNode { value: value, left: none, right: none, height: 1 };
if (self.root.is_none()) {
self.root = some(node);
} else {
var root_node: TreeNode<T> = self.root else {
return;
}
self.insert_recursive(root_node, value);
}
self.size = self.size + 1;
}
fn (self: BinarySearchTree<T>) insert_recursive(current: TreeNode<T>, value: T) {
if (current.left.is_none()) {
current.left = some(TreeNode { value: value, left: none, right: none, height: 1 });
} else {
var left_node: TreeNode<T> = current.left else {
return;
}
self.insert_recursive(left_node, value);
}
self.update_height(current);
}
fn (self: BinarySearchTree<T>) update_height(node: TreeNode<T>) {
var left_height: int = 0;
var right_height: int = 0;
if (node.left.is_some()) {
var left_node: TreeNode<T> = node.left else {
return;
}
left_height = left_node.height;
}
if (node.right.is_some()) {
var right_node: TreeNode<T> = node.right else {
return;
}
right_height = right_node.height;
}
if (left_height > right_height) {
node.height = left_height + 1;
} else {
node.height = right_height + 1;
}
}
pub fn (self: BinarySearchTree<T>) find(value: T) -> option<T> {
return self.find_recursive(self.root, value);
}
fn (self: BinarySearchTree<T>) find_recursive(current: option<TreeNode<T>>, value: T) -> option<T> {
if (current.is_none()) {
return none;
}
var node: TreeNode<T> = current else {
return none;
}
return self.find_recursive(node.left, value);
}
// =============================================================================
// Async HTTP Client
// =============================================================================
pub struct HttpHeaders {
pub headers: map<string, string>
}
pub fn (mut self: HttpHeaders) set(name: string, value: string) {
self.headers[name] = value;
}
pub fn (self: HttpHeaders) get(name: string) -> option<string> {
return self.headers[name];
}
pub struct HttpRequest {
pub method: string,
pub url: string,
pub headers: HttpHeaders,
pub body: option<bytes>,
pub timeout_ms: int
}
pub struct HttpResponse {
pub status_code: int,
pub status_text: string,
pub headers: HttpHeaders,
pub body: bytes,
pub elapsed_ms: int
}
pub fn (self: HttpResponse) is_success() -> bool {
return self.status_code >= 200 && self.status_code < 300;
}
pub fn (self: HttpResponse) is_redirect() -> bool {
return self.status_code >= 300 && self.status_code < 400;
}
pub fn (self: HttpResponse) is_client_error() -> bool {
return self.status_code >= 400 && self.status_code < 500;
}
pub fn (self: HttpResponse) is_server_error() -> bool {
return self.status_code >= 500;
}
interface HttpClient {
fn get(url: string) -> HttpResponse throws NetworkError;
fn post(url: string, body: bytes) -> HttpResponse throws NetworkError;
fn put(url: string, body: bytes) -> HttpResponse throws NetworkError;
fn delete(url: string) -> HttpResponse throws NetworkError;
fn request(req: HttpRequest) -> HttpResponse throws NetworkError;
}
pub struct SimpleHttpClient implements HttpClient {
pub base_url: string,
pub default_headers: HttpHeaders,
pub timeout_ms: int,
pub retry_count: int,
pub retry_delay_ms: int
}
pub fn (self: SimpleHttpClient) get(url: string) -> HttpResponse throws NetworkError {
var req: HttpRequest = HttpRequest {
method: "GET",
url: self.base_url + url,
headers: self.default_headers,
body: none,
timeout_ms: self.timeout_ms
};
return self.request(req);
}
pub fn (self: SimpleHttpClient) post(url: string, body: bytes) -> HttpResponse throws NetworkError {
var req: HttpRequest = HttpRequest {
method: "POST",
url: self.base_url + url,
headers: self.default_headers,
body: some(body),
timeout_ms: self.timeout_ms
};
return self.request(req);
}
pub fn (self: SimpleHttpClient) put(url: string, body: bytes) -> HttpResponse throws NetworkError {
var req: HttpRequest = HttpRequest {
method: "PUT",
url: self.base_url + url,
headers: self.default_headers,
body: some(body),
timeout_ms: self.timeout_ms
};
return self.request(req);
}
pub fn (self: SimpleHttpClient) delete(url: string) -> HttpResponse throws NetworkError {
var req: HttpRequest = HttpRequest {
method: "DELETE",
url: self.base_url + url,
headers: self.default_headers,
body: none,
timeout_ms: self.timeout_ms
};
return self.request(req);
}
pub fn (self: SimpleHttpClient) request(req: HttpRequest) -> HttpResponse throws NetworkError {
var attempts: int = 0;
while (attempts < self.retry_count) {
var response: HttpResponse = self.do_request(req);
if (response.is_success()) {
return response;
}
if (response.is_client_error()) {
throw NetworkError {
message: "Client error: " + response.status_text,
code: response.status_code,
retry_after: none
};
}
attempts = attempts + 1;
if (attempts < self.retry_count) {
sleep(self.retry_delay_ms);
}
}
throw NetworkError {
message: "Max retries exceeded",
code: -1,
retry_after: some(self.retry_delay_ms)
};
}
fn (self: SimpleHttpClient) do_request(req: HttpRequest) -> HttpResponse {
return HttpResponse {
status_code: 200,
status_text: "OK",
headers: HttpHeaders { headers: {} },
body: "" as bytes,
elapsed_ms: 0
};
}
extern fn sleep(ms: int) -> promise<unit>;
// =============================================================================
// Database Repository Pattern
// =============================================================================
interface Repository<T, ID> {
fn find_by_id(id: ID) -> option<T> throws DatabaseError;
fn find_all() -> [T] throws DatabaseError;
fn save(entity: T) -> T throws DatabaseError;
fn delete(id: ID) -> bool throws DatabaseError;
fn exists(id: ID) -> bool throws DatabaseError;
fn count() -> int throws DatabaseError;
}
pub struct UserRepository implements Repository<User, UserId> {
pub connection_string: string,
pub table_name: string
}
pub fn (self: UserRepository) find_by_id(id: UserId) -> option<User> throws DatabaseError {
var query: string = "SELECT * FROM " + self.table_name + " WHERE id = ?";
var result: [map<string, string>] = self.execute_query(query, [id.value]);
if (result.length == 0) {
return none;
}
return some(self.map_row_to_user(result[0]));
}
pub fn (self: UserRepository) find_all() -> [User] throws DatabaseError {
var query: string = "SELECT * FROM " + self.table_name;
var result: [map<string, string>] = self.execute_query(query, []);
var users: [User] = [];
for (row in result) {
users.push(self.map_row_to_user(row));
}
return users;
}
pub fn (self: UserRepository) save(entity: User) -> User throws DatabaseError {
var existing: option<User> = self.find_by_id(entity.id);
if (existing.is_some()) {
return self.update(entity);
}
return self.insert(entity);
}
fn (self: UserRepository) insert(entity: User) -> User throws DatabaseError {
var query: string = "INSERT INTO " + self.table_name + " (id, email, username) VALUES (?, ?, ?)";
self.execute_update(query, [entity.id.value, entity.email.to_string(), entity.username]);
return entity;
}
fn (self: UserRepository) update(entity: User) -> User throws DatabaseError {
var query: string = "UPDATE " + self.table_name + " SET email = ?, username = ? WHERE id = ?";
self.execute_update(query, [entity.email.to_string(), entity.username, entity.id.value]);
return entity;
}
pub fn (self: UserRepository) delete(id: UserId) -> bool throws DatabaseError {
var query: string = "DELETE FROM " + self.table_name + " WHERE id = ?";
var affected: int = self.execute_update(query, [id.value]);
return affected > 0;
}
pub fn (self: UserRepository) exists(id: UserId) -> bool throws DatabaseError {
var query: string = "SELECT COUNT(*) FROM " + self.table_name + " WHERE id = ?";
var result: [map<string, string>] = self.execute_query(query, [id.value]);
var count_str: string = result[0]["count"].or_default("0");
return count_str > "0";
}
pub fn (self: UserRepository) count() -> int throws DatabaseError {
var query: string = "SELECT COUNT(*) as cnt FROM " + self.table_name;
var result: [map<string, string>] = self.execute_query(query, []);
var cnt_str: string = result[0]["cnt"].or_default("0");
return cnt_str as int;
}
fn (self: UserRepository) execute_query(query: string, params: [string]) -> [map<string, string>] throws DatabaseError {
return [];
}
fn (self: UserRepository) execute_update(query: string, params: [string]) -> int throws DatabaseError {
return 1;
}
fn (self: UserRepository) map_row_to_user(row: map<string, string>) -> User {
var id_str: string = row["id"].or_default("");
var username_str: string = row["username"].or_default("");
return User {
id: UserId { value: id_str },
email: Email { local: "user", domain: "example.com" },
username: username_str,
password_hash: "",
first_name: none,
last_name: none,
address: none,
phone: none,
status: UserStatus::Active,
roles: [UserRole::User],
metadata: {},
created_at: 0,
updated_at: 0,
last_login: none
};
}
// =============================================================================
// Event System
// =============================================================================
interface Event {
fn event_type() -> string;
fn timestamp() -> int;
fn payload() -> map<string, string>;
}
interface EventHandler<E: Event> {
fn handle(event: E) throws;
}
interface EventBus {
fn subscribe<E: Event>(handler: EventHandler<E>);
fn publish<E: Event>(event: E);
}
pub struct UserCreatedEvent implements Event {
pub user_id: UserId,
pub email: string,
pub created_at: int
}
pub fn (self: UserCreatedEvent) event_type() -> string {
return "user.created";
}
pub fn (self: UserCreatedEvent) timestamp() -> int {
return self.created_at;
}
pub fn (self: UserCreatedEvent) payload() -> map<string, string> {
return {
"user_id": self.user_id.value,
"email": self.email
};
}
pub struct UserDeletedEvent implements Event {
pub user_id: UserId,
pub reason: string,
pub deleted_at: int
}
pub fn (self: UserDeletedEvent) event_type() -> string {
return "user.deleted";
}
pub fn (self: UserDeletedEvent) timestamp() -> int {
return self.deleted_at;
}
pub fn (self: UserDeletedEvent) payload() -> map<string, string> {
return {
"user_id": self.user_id.value,
"reason": self.reason
};
}
// =============================================================================
// Functional Programming Utilities
// =============================================================================
pub fn map_array<T, U>(arr: [T], f: fn(T) -> U) -> [U] {
var result: [U] = [];
for (item in arr) {
result.push(f(item));
}
return result;
}
pub fn filter_array<T>(arr: [T], predicate: fn(T) -> bool) -> [T] {
var result: [T] = [];
for (item in arr) {
if (predicate(item)) {
result.push(item);
}
}
return result;
}
pub fn reduce_array<T, U>(arr: [T], initial: U, reducer: fn(U, T) -> U) -> U {
var acc: U = initial;
for (item in arr) {
acc = reducer(acc, item);
}
return acc;
}
pub fn find_first<T>(arr: [T], predicate: fn(T) -> bool) -> option<T> {
for (item in arr) {
if (predicate(item)) {
return some(item);
}
}
return none;
}
pub fn any<T>(arr: [T], predicate: fn(T) -> bool) -> bool {
for (item in arr) {
if (predicate(item)) {
return true;
}
}
return false;
}
pub fn all<T>(arr: [T], predicate: fn(T) -> bool) -> bool {
for (item in arr) {
if (!predicate(item)) {
return false;
}
}
return true;
}
pub struct Pair<A, B> {
pub first: A,
pub second: B
}
pub fn zip<A, B>(a: [A], b: [B]) -> [Pair<A, B>] {
var result: [Pair<A, B>] = [];
var i: int = 0;
while (i < a.length && i < b.length) {
result.push(Pair { first: a[i], second: b[i] });
i = i + 1;
}
return result;
}
pub fn flatten<T>(nested: [[T]]) -> [T] {
var result: [T] = [];
for (inner in nested) {
for (item in inner) {
result.push(item);
}
}
return result;
}
// Generic function with trait bound - uses compare from Comparable
pub fn max_value<T: Comparable<T>>(a: T, b: T) -> T {
if (a.compare(b) > 0) {
return a;
}
return b;
}
// Generic function with trait bound - uses compare from Comparable
pub fn min_value<T: Comparable<T>>(a: T, b: T) -> T {
if (a.compare(b) < 0) {
return a;
}
return b;
}
// Note: compose and curry2 require advanced function type syntax not yet supported
// pub fn compose<A, B, C>(f: fn(B) -> C, g: fn(A) -> B) -> fn(A) -> C {
// return |a: A| f(g(a));
// }
//
// pub fn curry2<A, B, C>(f: fn(A, B) -> C) -> fn(A) -> fn(B) -> C {
// return |a: A| |b: B| f(a, b);
// }
// =============================================================================
// Concurrency Patterns
// =============================================================================
pub struct Mutex<T> {
pub value: T,
pub locked: bool
}
pub fn (mut self: Mutex<T>) lock() -> T {
while (self.locked) {
yield_now();
}
self.locked = true;
return self.value;
}
pub fn (mut self: Mutex<T>) unlock() {
self.locked = false;
}
extern fn yield_now() -> promise<unit>;
pub struct Channel<T> {
pub buffer: [T],
pub capacity: int,
pub closed: bool
}
pub fn (mut self: Channel<T>) send(value: T) -> bool {
if (self.closed) {
return false;
}
while (self.buffer.length >= self.capacity) {
yield_now();
}
self.buffer.push(value);
return true;
}
pub fn (mut self: Channel<T>) receive() -> option<T> {
while (self.buffer.length == 0 && !self.closed) {
yield_now();
}
if (self.buffer.length == 0) {
return none;
}
var value: option<T> = self.buffer.pop();
return value;
}
pub fn (mut self: Channel<T>) close() {
self.closed = true;
}
// =============================================================================
// Main Entry Point
// =============================================================================
fn main() {
var client: SimpleHttpClient = SimpleHttpClient {
base_url: "https://api.example.com",
default_headers: HttpHeaders { headers: { "Content-Type": "application/json" } },
timeout_ms: 30000,
retry_count: 3,
retry_delay_ms: 1000
};
var user_repo: UserRepository = UserRepository {
connection_string: "postgres://localhost/mydb",
table_name: "users"
};
var user_id: UserId = UserId { value: "user-123" };
var user_opt: option<User> = user_repo.find_by_id(user_id);
var user: User = user_opt else {
printf("User not found");
return;
}
printf("Found user: {}", user.full_name());
var response: HttpResponse = client.get("/users/" + user_id.value);
if (response.is_success()) {
printf("API call successful: {} {}", response.status_code, response.status_text);
}
var numbers: [int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var doubled: [int] = [];
for (n in numbers) {
doubled.push(n * 2);
}
var evens: [int] = [];
for (n in numbers) {
if (n % 2 == 0) {
evens.push(n);
}
}
var sum: int = 0;
for (n in numbers) {
sum = sum + n;
}
printf("Doubled: {}", doubled);
printf("Evens: {}", evens);
printf("Sum: {}", sum);
var users: [User] = [];
var admins: [User] = [];
for (u in users) {
if (u.is_admin()) {
admins.push(u);
}
}
var active_admins: [User] = [];
for (u in admins) {
if (u.is_active()) {
active_admins.push(u);
}
}
printf("Active admins: {}", active_admins.length);
// Note: promise type and async task patterns removed as async/await is not supported
// Running synchronous requests instead
for (i: int in 0..10) {
var response: HttpResponse = client.get("/items/" + (i as string));
println("Task completed: {}", response.status_code);
}
}