|
| 1 | +#![no_main] |
| 2 | +use libfuzzer_sys::fuzz_target; |
| 3 | + |
| 4 | +/// Replicate the cursor helpers from app.rs to fuzz the same logic. |
| 5 | +fn next_char_pos(buf: &str, pos: usize) -> usize { |
| 6 | + if pos >= buf.len() { |
| 7 | + return buf.len(); |
| 8 | + } |
| 9 | + pos + buf[pos..].chars().next().map_or(1, |c| c.len_utf8()) |
| 10 | +} |
| 11 | + |
| 12 | +fn prev_char_pos(buf: &str, pos: usize) -> usize { |
| 13 | + if pos == 0 { |
| 14 | + return 0; |
| 15 | + } |
| 16 | + pos - buf[..pos].chars().next_back().map_or(1, |c| c.len_utf8()) |
| 17 | +} |
| 18 | + |
| 19 | +fuzz_target!(|data: &[u8]| { |
| 20 | + // Need at least 1 byte for the operation selector |
| 21 | + if data.is_empty() { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // Interpret the first bytes as initial UTF-8 buffer content |
| 26 | + let split = data.len() / 2; |
| 27 | + let buf_bytes = &data[..split]; |
| 28 | + let ops = &data[split..]; |
| 29 | + |
| 30 | + let Ok(initial) = std::str::from_utf8(buf_bytes) else { |
| 31 | + return; |
| 32 | + }; |
| 33 | + |
| 34 | + let mut buffer = initial.to_string(); |
| 35 | + let mut cursor: usize = 0; |
| 36 | + |
| 37 | + // Apply a sequence of editing operations driven by the fuzzer |
| 38 | + for &op in ops { |
| 39 | + match op % 8 { |
| 40 | + // Move right |
| 41 | + 0 => cursor = next_char_pos(&buffer, cursor), |
| 42 | + // Move left |
| 43 | + 1 => cursor = prev_char_pos(&buffer, cursor), |
| 44 | + // Backspace |
| 45 | + 2 => { |
| 46 | + if cursor > 0 { |
| 47 | + cursor = prev_char_pos(&buffer, cursor); |
| 48 | + if cursor < buffer.len() && buffer.is_char_boundary(cursor) { |
| 49 | + buffer.remove(cursor); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + // Delete |
| 54 | + 3 => { |
| 55 | + if cursor < buffer.len() && buffer.is_char_boundary(cursor) { |
| 56 | + buffer.remove(cursor); |
| 57 | + } |
| 58 | + } |
| 59 | + // Insert ASCII char |
| 60 | + 4 => { |
| 61 | + if buffer.is_char_boundary(cursor) { |
| 62 | + buffer.insert(cursor, 'a'); |
| 63 | + cursor += 1; |
| 64 | + } |
| 65 | + } |
| 66 | + // Insert multi-byte char |
| 67 | + 5 => { |
| 68 | + if buffer.is_char_boundary(cursor) { |
| 69 | + buffer.insert(cursor, '\u{1F600}'); // 4-byte emoji |
| 70 | + cursor += 4; |
| 71 | + } |
| 72 | + } |
| 73 | + // Home |
| 74 | + 6 => cursor = 0, |
| 75 | + // End |
| 76 | + 7 => cursor = buffer.len(), |
| 77 | + _ => unreachable!(), |
| 78 | + } |
| 79 | + |
| 80 | + // Invariant: cursor must always be at a valid char boundary |
| 81 | + assert!( |
| 82 | + cursor <= buffer.len(), |
| 83 | + "cursor {cursor} past end {}", |
| 84 | + buffer.len() |
| 85 | + ); |
| 86 | + if cursor < buffer.len() { |
| 87 | + assert!( |
| 88 | + buffer.is_char_boundary(cursor), |
| 89 | + "cursor {cursor} not on char boundary" |
| 90 | + ); |
| 91 | + } |
| 92 | + } |
| 93 | +}); |
0 commit comments