Categories
Tags
3d algorithms alignment analyze APIT Arc Architecture arm ascii assembly asynchronous base64 BitHacks Blogging box c c23 clang clang-format client clippy cmake compiler Computer concat concurrency const_fn constexpr contravariant cos covariant cpp cpu crate CS Customization cybersecurity DataStructure db debugging Demo deserialization discrete doc DP drawio dtruss Dynamic emulator example Example FFI flamegraph flat_map fold format FP fsanitize Functional FunctionalProgramming functions futures Fuwari game GATs gcc gccrs generics gitignore glibc GUI hacking hashmap haskell heap hyperfine Imperative interop invariant iterator join justfile kernel LaTeX leak LFU linux lto MachineLearning macOS map Markdown math ML mmap mod nc OnceLock optimization OS ownership panic parallels perf physics pin postgresql product profiling pub radare2 rayon release reverse RPIT rust sanitizer Science science serialization server shift sin size SmallProjects socket std strace String StringView strip strlen struct sum super surrealdb SWAR swisstable synchronous tan thread time toml tracing traits triangulation uint32_t UnsafeRust utf16 utf8 Video vulkan wsl x86_64 xilem zig
243 words
1 minutes
StringView
link
C vs Rust pointer comparison
| Concept | C | Rust |
|---|---|---|
| pointer to struct | String_View * | &mut StringView |
| arrow | sv->count | sv.count |
| address | &s | &mut s |
| modify | pointer | mutable reference |
| pointer math | allowed | not allowed |
| slicing | manual | built-in |
C code
// main.c
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
const char *data;
size_t count;
} String_View;
// Hello, World0...
// ^ ^
String_View sv(const char *cstr) {
return (String_View){
.data = cstr,
.count = strlen(cstr),
};
}
void sv_chop_left(String_View *sv, size_t n) {
if (n > sv->count)
n = sv->count;
sv->count -= n;
sv->data += n;
}
void sv_chop_right(String_View *sv, size_t n) {
if (n > sv->count)
n = sv->count;
sv->count -= n;
}
int main() {
String_View s = sv("Hello, World");
sv_chop_right(&s, 3);
sv_chop_left(&s, 2);
printf("%.*s\n", (int)s.count, s.data);
return 0;
}Rust code
// main.rs
#[derive(Debug, Clone, Copy)]
struct StringView<'a> {
data: &'a str,
count: usize,
}
impl<'a> StringView<'a> {
fn sv(s: &'a str) -> Self {
Self {
data: s,
count: s.len(),
}
}
fn sv_chop_left(sv: &mut Self, n: usize) {
let n = n.min(sv.count);
sv.data = &sv.data[n..];
sv.count -= n;
}
fn sv_chop_right(sv: &mut Self, n: usize) {
let n = n.min(sv.count);
sv.count -= n;
sv.data = &sv.data[..sv.count];
}
}
fn main() {
let mut s = StringView::sv("Hello, World");
StringView::sv_chop_right(&mut s, 3);
StringView::sv_chop_left(&mut s, 2);
println!("{}", s.data);
}- Result
llo, Wo