Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Last active May 23, 2025 22:22
Show Gist options
  • Save jweinst1/05045423520cdd219654bdc75fbc7531 to your computer and use it in GitHub Desktop.
Save jweinst1/05045423520cdd219654bdc75fbc7531 to your computer and use it in GitHub Desktop.
indexing a string in rust.
use std::fs::File;
use std::io::prelude::*;
use std::io::SeekFrom;
use std::fs::OpenOptions;
#[derive(Debug)]
struct Seg(usize, usize);
impl Seg {
fn contains(&self, text:&[u8], term:&[u8]) -> bool {
let mut mode = false;
let mut idx = 0;
for i in self.0..(self.1 + 1) {
println!("i is {:?}", i);
if mode {
if text[i] == term[idx] {
idx += 1;
if idx == term.len() {
return true;
}
} else {
mode = false;
idx = 0;
}
} else {
if text[i] == term[0] {
println!("Got begin");
mode = true;
idx += 1;
}
}
}
false
}
}
fn get_indexes(text:&[u8], delim:u8) -> Vec<Seg> {
let mut v = Vec::new();
let mut last_idx = 0;
for i in 0..text.len() {
if text[i] == delim && i - last_idx > 1 {
v.push(Seg(last_idx + 1, i - 1));
last_idx = i;
}
}
if (text.len() - 1 - last_idx) > 0 {
v.push(Seg(last_idx + 1, text.len() - 1));
}
return v;
}
fn main() {
let foo = "\nfoobar\nfoobar\n4".to_string();
let segs = get_indexes(foo.as_bytes(), b'\n');
println!("{:?}", segs);
println!("{}", segs[0].contains(foo.as_bytes(),b"foobar"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment