aboutsummaryrefslogtreecommitdiff
path: root/examples/example.ct
diff options
context:
space:
mode:
authorKimplul <kimi.h.kuparinen@gmail.com>2023-03-07 02:18:26 +0200
committerKimplul <kimi.h.kuparinen@gmail.com>2023-03-07 02:18:26 +0200
commitae5fee63f160643a397d18e9e0658275606bc4d4 (patch)
treef68af302374f9ae3c9dbb28dab5547036252d559 /examples/example.ct
downloadek-ae5fee63f160643a397d18e9e0658275606bc4d4.tar.gz
ek-ae5fee63f160643a397d18e9e0658275606bc4d4.zip
initial commit
Diffstat (limited to 'examples/example.ct')
-rw-r--r--examples/example.ct97
1 files changed, 97 insertions, 0 deletions
diff --git a/examples/example.ct b/examples/example.ct
new file mode 100644
index 0000000..ce3e4e7
--- /dev/null
+++ b/examples/example.ct
@@ -0,0 +1,97 @@
+/* String example */
+
+pub struct string {
+ len usize;
+ buf *u8;
+}
+
+pub init(mut s *string)
+{
+ s.len = 0;
+ s.buf = null;
+}
+
+pub deinit(mut s *string)
+{
+ dealloc(s.buf);
+}
+
+pub init(mut s *string, u *u8)
+{
+ len usize = 0;
+ r any = u;
+ while r++ {len++;}
+
+ s.len = len;
+ s.buf = alloc(s.len);
+ memcpy(s.buf, u);
+}
+
+pub copy(mut r *string, s *string) *string
+{
+ dealloc(r.buf);
+ r.len = s.len;
+ r.buf = alloc(r.len);
+ memcpy(r.buf, s.buf);
+}
+
+pub move(mut r *string, mut s *string) *string
+{
+ dealloc(r.buf);
+ r.len = s.len;
+ r.buf = s.buf;
+ s.buf = null;
+ s.len = 0;
+}
+
+pub length(s *string) usize
+{
+ return s.len;
+}
+
+pub index(s *string, i usize) u8
+{
+ assert(i < len, "index %zu out of bounds\n", i);
+ return s.buf[i];
+}
+
+pub add(r *string, a *string, b *string)
+{
+ len any = length(a) + length(b);
+ buf any = alloc(l);
+
+ if r.buf == a.buf {
+ dealloc(a.buf);
+ } else if r.buf == b.buf {
+ dealloc(b.buf);
+ }
+
+ r.buf = buf;
+ r.len = len;
+}
+
+pub define new(x ...args)
+{
+ x = alloc(sizeof(x));
+ init(@ ...args);
+}
+
+pub define ctx(x ...args)
+{
+ init(&x ...args);
+ defer(deinit(@));
+}
+
+main(argc i32, argv [argc] * u8)
+{
+ something = argv[10]; // run type bounds checking for ranged array?
+ // will not be automatically freed
+ new(a *string);
+ new(b *string, "hello");
+ c string; // undefined state
+ // will be automatically 'freed'
+ ctx(c string);
+ ctx(v vec<string>);
+ append(v, a);
+ append(v, c);
+}