Fix byte safety, ownership and parser failures

8317059e672b20878ee73b04fdaa917be7b6c8a1
Validate byte layouts and make unchecked byte conversions unsafe. Drop
array elements once, track UTF-8 cursor offsets, and stop parser
repetition when it consumes no input.

Validate image dimensions before allocation and return an error for
truncated font headers.
Alexis Sellier committed ago 1 parent 8ea131d9
ombre-derive/src/lib.rs +35 -15
67 67
                format: <#ty as ombre::gfx::ToVertexFormat>::FORMAT,
68 68
            }
69 69
        }
70 70
    });
71 71
72 +
    let packed = packed_impl(&ast);
72 73
    let expanded = quote! {
73 74
        impl ombre::gfx::VertexAttributes for #name {
74 75
            fn attributes() -> &'static [ombre::gfx::VertexAttribute] {
75 76
                static ATTRS: &[ombre::gfx::VertexAttribute] = &[#(#attrs),*];
76 77
                ATTRS
77 78
            }
78 79
        }
79 -
        unsafe impl ombre::bytes::Packed for #name {}
80 +
        #packed
80 81
    };
81 82
    TokenStream::from(expanded)
82 83
}
83 84
84 85
/// Derive macro for implementing the `UniformBlock` trait.
145 146
146 147
    let (_, ty_generics, where_clause) = ast.generics.split_for_impl();
147 148
    let const_params = ast.generics.const_params().collect::<Vec<_>>();
148 149
    let lifetime_params = ast.generics.lifetimes().collect::<Vec<_>>();
149 150
151 +
    let packed = packed_impl(&ast);
150 152
    let expanded = quote! {
151 153
        impl<'block, #(#lifetime_params,)* #(#const_params,)*> ombre::gfx::UniformBlock<'block>
152 154
        for #name #ty_generics #where_clause {
153 155
            fn layout() -> ombre::gfx::UniformBlockLayout<'block> {
154 156
                let uniforms = &[#(#descriptors),*];
155 157
                ombre::gfx::UniformBlockLayout {
156 158
                    uniforms
157 159
                }
158 160
            }
159 161
        }
160 -
        unsafe impl<#(#lifetime_params,)* #(#const_params,)*> ombre::bytes::Packed
161 -
        for #name #ty_generics #where_clause {}
162 +
        #packed
162 163
    };
163 164
164 165
    TokenStream::from(expanded)
165 166
}
166 167
237 238
238 239
/// Derive macro for implementing the `Packed` trait.
239 240
#[proc_macro_derive(Packed)]
240 241
pub fn derive_packed(input: TokenStream) -> TokenStream {
241 242
    let ast = parse_macro_input!(input as DeriveInput);
243 +
    if !matches!(ast.data, Data::Struct(_)) {
244 +
        return Error::new_spanned(&ast, "`Packed` can only be derived for structs")
245 +
            .to_compile_error()
246 +
            .into();
247 +
    }
248 +
    let packed = packed_impl(&ast);
249 +
    quote!(#packed).into()
250 +
}
251 +
252 +
/// Generate a checked byte layout for a struct.
253 +
fn packed_impl(ast: &DeriveInput) -> impl quote::ToTokens {
242 254
    let name = &ast.ident;
243 -
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
244 -
    let data = match ast.data {
245 -
        Data::Struct(data) => data,
246 -
        _ => {
247 -
            return Error::new_spanned(&ast, "`Packed` can only be derived for structs")
248 -
                .to_compile_error()
249 -
                .into();
250 -
        }
255 +
    let Data::Struct(data) = &ast.data else {
256 +
        unreachable!("packed_impl requires a struct");
251 257
    };
252 -
    let field_types = data.fields.iter().map(|f| &f.ty);
258 +
    let field_types: Vec<_> = data.fields.iter().map(|field| &field.ty).collect();
259 +
    let mut generics = ast.generics.clone();
260 +
    for ty in &field_types {
261 +
        generics
262 +
            .make_where_clause()
263 +
            .predicates
264 +
            .push(syn::parse_quote!(#ty: ombre::bytes::Packed));
265 +
    }
266 +
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
253 267
254 268
    quote! {
255 -
        unsafe impl #impl_generics ombre::bytes::Packed for #name #ty_generics #where_clause
256 -
        where #(#field_types: ombre::bytes::Packed,)* {}
269 +
        unsafe impl #impl_generics ombre::bytes::Packed for #name #ty_generics #where_clause {
270 +
            const VALID_LAYOUT: () = {
271 +
                #(let () = <#field_types as ombre::bytes::Packed>::VALID_LAYOUT;)*
272 +
                assert!(
273 +
                    ::std::mem::size_of::<Self>() == 0usize #(+ ::std::mem::size_of::<#field_types>())*,
274 +
                    "Packed type contains padding"
275 +
                );
276 +
            };
277 +
        }
257 278
    }
258 -
    .into()
259 279
}
ombre/src/array.rs +44 -3
1 1
//! A fixed-capacity array implementation with runtime length tracking.
2 2
use std::error::Error;
3 3
use std::fmt;
4 -
use std::mem::MaybeUninit;
4 +
use std::mem::{ManuallyDrop, MaybeUninit};
5 5
6 6
/// Error type for [`Array`] operations.
7 7
#[derive(Debug, Clone, PartialEq, Eq)]
8 8
pub enum ArrayError {
9 9
    /// Returned when attempting to add elements to a full array.
205 205
    type Item = T;
206 206
    type IntoIter = IntoIter<T, N>;
207 207
208 208
    fn into_iter(self) -> Self::IntoIter {
209 209
        IntoIter {
210 -
            vec: self,
210 +
            vec: ManuallyDrop::new(self),
211 211
            index: 0,
212 212
        }
213 213
    }
214 214
}
215 215
216 +
/// An iterator that owns the elements of a fixed-capacity array.
216 217
pub struct IntoIter<T, const N: usize> {
217 -
    vec: Array<T, N>,
218 +
    /// Array storage. The iterator drops the elements that it has not yielded.
219 +
    vec: ManuallyDrop<Array<T, N>>,
220 +
    /// Index of the next element to yield.
218 221
    index: usize,
219 222
}
220 223
221 224
impl<T, const N: usize> Iterator for IntoIter<T, N> {
222 225
    type Item = T;
236 239
        let remaining = self.vec.len - self.index;
237 240
        (remaining, Some(remaining))
238 241
    }
239 242
}
240 243
244 +
impl<T, const N: usize> Drop for IntoIter<T, N> {
245 +
    fn drop(&mut self) {
246 +
        for item in self.by_ref() {
247 +
            drop(item);
248 +
        }
249 +
    }
250 +
}
251 +
241 252
#[cfg(test)]
242 253
#[allow(clippy::unwrap_used)]
243 254
mod tests {
244 255
    use super::*;
245 256
333 344
        assert_eq!(iter.next(), Some(2));
334 345
        assert_eq!(iter.next(), Some(3));
335 346
        assert_eq!(iter.next(), None);
336 347
    }
337 348
349 +
    #[test]
350 +
    fn test_iterator_drops_each_element_once() {
351 +
        use std::cell::Cell;
352 +
353 +
        #[derive(Debug)]
354 +
        struct DropCounter<'a>(&'a Cell<usize>);
355 +
356 +
        impl Drop for DropCounter<'_> {
357 +
            fn drop(&mut self) {
358 +
                self.0.set(self.0.get() + 1);
359 +
            }
360 +
        }
361 +
362 +
        for consumed in 0..=3 {
363 +
            let drops = Cell::new(0);
364 +
            let mut array: Array<_, 3> = Array::new();
365 +
            array.extend((0..3).map(|_| DropCounter(&drops))).unwrap();
366 +
367 +
            let mut iter = array.into_iter();
368 +
            for _ in 0..consumed {
369 +
                drop(iter.next().unwrap());
370 +
            }
371 +
            assert_eq!(drops.get(), consumed);
372 +
            assert_eq!(iter.size_hint(), (3 - consumed, Some(3 - consumed)));
373 +
374 +
            drop(iter);
375 +
            assert_eq!(drops.get(), 3);
376 +
        }
377 +
    }
378 +
338 379
    #[test]
339 380
    fn test_drop() {
340 381
        use std::rc::Rc;
341 382
342 383
        let mut array: Array<Rc<i32>, 2> = Array::new();
ombre/src/bytes.rs +62 -22
6 6
7 7
/// Used when an empty [`AsBytes`] instance is needed.
8 8
#[derive(Debug, Clone, Copy, Default)]
9 9
pub struct Empty;
10 10
11 -
/// Marker trait for types that are packed and can be safely
12 -
/// converted to a byte slice.
11 +
/// Types with a memory layout that can be viewed as bytes.
13 12
///
14 13
/// # Safety
15 14
///
16 -
/// Types which derive `repr(C)` and do not have any pointers or references can safely implement
17 -
/// this trait.
18 -
pub unsafe trait Packed {}
15 +
/// After `VALID_LAYOUT` is evaluated, every byte in a value must be initialized.
16 +
/// Shared byte access must not allow the value to change through interior mutability.
17 +
/// Byte conversions must evaluate `VALID_LAYOUT` before they access the value.
18 +
///
19 +
/// ```compile_fail
20 +
/// use ombre::bytes::AsBytes;
21 +
/// #[repr(C)]
22 +
/// #[derive(ombre::Packed)]
23 +
/// struct Padded<T: ombre::bytes::Packed> { small: u8, large: T }
24 +
/// let value = [Padded { small: 1, large: 2u32 }];
25 +
/// let _ = value.as_slice().as_bytes();
26 +
/// ```
27 +
pub unsafe trait Packed {
28 +
    /// Compile-time check for initialized bytes in the memory layout.
29 +
    const VALID_LAYOUT: () = ();
30 +
}
19 31
20 -
unsafe impl<T, const N: usize> Packed for [T; N] where T: Packed {}
32 +
unsafe impl<T: Packed, const N: usize> Packed for [T; N] {
33 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
34 +
}
21 35
unsafe impl Packed for u8 {}
22 36
unsafe impl Packed for u16 {}
23 37
unsafe impl Packed for u32 {}
24 38
unsafe impl Packed for u64 {}
25 39
unsafe impl Packed for i8 {}
29 43
unsafe impl Packed for f32 {}
30 44
unsafe impl Packed for f64 {}
31 45
unsafe impl Packed for crate::gfx::Rgba8 {}
32 46
unsafe impl Packed for crate::gfx::Rgb8 {}
33 47
unsafe impl Packed for crate::gfx::Rgba<f32> {}
34 -
unsafe impl<T> Packed for crate::gfx::Size<T> where T: Packed {}
35 -
unsafe impl<T> Packed for crate::gfx::Point2D<T> where T: Packed {}
36 -
unsafe impl<T> Packed for crate::gfx::Vector2D<T> where T: Packed {}
37 -
unsafe impl<T> Packed for crate::gfx::Vector3D<T> where T: Packed {}
38 -
unsafe impl<T> Packed for crate::gfx::Vector4D<T> where T: Packed {}
48 +
unsafe impl<T: Packed> Packed for crate::gfx::Size<T> {
49 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
50 +
}
51 +
unsafe impl<T: Packed> Packed for crate::gfx::Point2D<T> {
52 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
53 +
}
54 +
unsafe impl<T: Packed> Packed for crate::gfx::Vector2D<T> {
55 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
56 +
}
57 +
unsafe impl<T: Packed> Packed for crate::gfx::Vector3D<T> {
58 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
59 +
}
60 +
unsafe impl<T: Packed> Packed for crate::gfx::Vector4D<T> {
61 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
62 +
}
39 63
unsafe impl<S, D> Packed for crate::gfx::Transform2D<S, D> {}
40 -
unsafe impl<S, D> Packed for crate::gfx::Transform3D<S, D> {}
64 +
unsafe impl<T: Packed, S, D> Packed for crate::gfx::Transform3D<T, S, D> {
65 +
    const VALID_LAYOUT: () = T::VALID_LAYOUT;
66 +
}
41 67
42 68
/// Types that can be represented as a `u8` slice.
43 69
///
44 70
/// # Safety
45 71
///
65 91
impl<T> AsBytes for T
66 92
where
67 93
    T: Packed,
68 94
{
69 95
    fn as_bytes(&self) -> &[u8] {
96 +
        let () = T::VALID_LAYOUT;
70 97
        unsafe { slice::from_raw_parts(self as *const Self as *const u8, mem::size_of::<Self>()) }
71 98
    }
72 99
}
73 100
74 101
impl<T: Packed> AsBytes for &[T] {
75 102
    fn as_bytes(&self) -> &[u8] {
103 +
        let () = T::VALID_LAYOUT;
76 104
        unsafe { slice::from_raw_parts(self.as_ptr() as *const u8, std::mem::size_of_val(*self)) }
77 105
    }
78 106
}
79 107
80 108
impl<T: Packed> AsBytes for [T] {
81 109
    fn as_bytes(&self) -> &[u8] {
110 +
        let () = T::VALID_LAYOUT;
82 111
        unsafe { slice::from_raw_parts(self.as_ptr() as *const u8, std::mem::size_of_val(self)) }
83 112
    }
84 113
}
85 114
86 115
/// Types that can be represented as a mutable `u8` slice.
87 116
pub trait AsBytesMut {
88 117
    /// Return a mutable byte slice representation.
89 -
    fn as_bytes_mut(&mut self) -> &mut [u8];
118 +
    ///
119 +
    /// # Safety
120 +
    ///
121 +
    /// Every byte in the slice must be initialized. All writes must leave the
122 +
    /// source elements valid, including their pointers and ownership state.
123 +
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8];
90 124
}
91 125
92 126
impl<T> AsBytesMut for &mut [T] {
93 -
    fn as_bytes_mut(&mut self) -> &mut [u8] {
94 -
        let (head, aligned, tail) = unsafe { self.align_to_mut::<u8>() };
95 -
96 -
        assert!(head.is_empty());
97 -
        assert!(tail.is_empty());
98 -
99 -
        aligned
127 +
    unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
128 +
        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().cast(), mem::size_of_val(*self)) }
100 129
    }
101 130
}
102 131
103 132
/// Extension trait for [`io::Read`] that provides methods for reading
104 133
/// primitive types in different endianness.
250 279
251 280
/// Align a byte slice to any slice type.
252 281
///
253 282
/// # Panics
254 283
///
255 -
/// If the byte slice length is not a multiple of the size of a `T`.
256 -
pub fn align_to<T>(bytes: &[u8]) -> &[T] {
284 +
/// If `T` has zero size, the slice is not aligned for `T`, or its length is
285 +
/// not a multiple of the size of `T`.
286 +
///
287 +
/// # Safety
288 +
///
289 +
/// The bytes must contain valid values of `T`. The returned references must
290 +
/// satisfy the aliasing and lifetime rules for `T`.
291 +
pub unsafe fn align_to<T>(bytes: &[u8]) -> &[T] {
292 +
    assert_ne!(mem::size_of::<T>(), 0, "align_to: zero-sized element type");
293 +
    assert!(
294 +
        bytes.as_ptr().cast::<T>().is_aligned(),
295 +
        "align_to: unaligned byte slice"
296 +
    );
257 297
    if bytes.len() % mem::size_of::<T>() != 0 {
258 298
        panic!(
259 299
            "{}::align_to: byte slice length {} is not a multiple of the size of a {}",
260 300
            module_path!(),
261 301
            bytes.len(),
ombre/src/gfx/color.rs +4 -1
51 51
    pub const fn alpha(self, a: u8) -> Self {
52 52
        Self::new(self.r, self.g, self.b, a)
53 53
    }
54 54
55 55
    /// Given a byte slice, returns a slice of [`Rgba8`] values.
56 -
    pub fn align<'a, S: 'a, T: AsRef<[S]> + ?Sized>(bytes: &'a T) -> &'a [Rgba8] {
56 +
    pub fn align<'a, S: crate::bytes::Packed + 'a, T: AsRef<[S]> + ?Sized>(
57 +
        bytes: &'a T,
58 +
    ) -> &'a [Rgba8] {
59 +
        let () = S::VALID_LAYOUT;
57 60
        let bytes = bytes.as_ref();
58 61
        let (head, body, tail) = unsafe { bytes.align_to::<Rgba8>() };
59 62
60 63
        if !(head.is_empty() && tail.is_empty()) {
61 64
            panic!("Rgba8::align: input is not a valid `Rgba8` buffer");
ombre/src/gfx/font.rs +2 -1
80 80
        assert!(
81 81
            matches!(format, FontFormat::UF2),
82 82
            "Only UF2 fonts are currently supported"
83 83
        );
84 84
85 -
        let (widths, glyphs) = bytes.split_at(N);
85 +
        let (widths, glyphs) =
86 +
            bytes.split_at_checked(N).ok_or(FontError::ByteLength(bytes.len()))?;
86 87
        let (head, tiles, tail) = unsafe { glyphs.align_to::<[u8; T]>() };
87 88
88 89
        if !head.is_empty() || !tail.is_empty() {
89 90
            return Err(FontError::ByteLength(glyphs.len()));
90 91
        }
ombre/src/gfx/image.rs +8 -5
69 69
    /// Create a new image from pixels and dimensions.
70 70
    pub fn new(pixels: impl Into<Arc<[Rgba8]>>, size: impl Into<Size<u32>>) -> Self {
71 71
        let size = size.into();
72 72
        let pixels = pixels.into();
73 73
74 -
        assert_eq!(size.area() as usize, pixels.len());
74 +
        assert_eq!(size.w as usize * size.h as usize, pixels.len());
75 75
76 76
        Self { size, pixels }
77 77
    }
78 78
79 79
    /// An empty image.
133 133
    fn decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
134 134
        let magic: [u8; 4] = Decode::decode(reader)?;
135 135
        if magic != MAGIC {
136 136
            return Err(io::ErrorKind::InvalidData.into());
137 137
        }
138 -
        let w = reader.read_u32_be()? as usize;
139 -
        let h = reader.read_u32_be()? as usize;
138 +
        let w = reader.read_u32_be()?;
139 +
        let h = reader.read_u32_be()?;
140 140
        let s = Size::new(w, h);
141 -
        let n = s.area();
141 +
        let n = (w as usize)
142 +
            .checked_mul(h as usize)
143 +
            .filter(|&n| n <= isize::MAX as usize / std::mem::size_of::<Rgba8>())
144 +
            .ok_or(io::ErrorKind::InvalidData)?;
142 145
143 -
        let mut pixels = Vec::with_capacity(n);
146 +
        let mut pixels = Vec::new();
144 147
        while pixels.len() < n {
145 148
            let pixel = Rgba8::decode(reader)?;
146 149
            pixels.push(pixel);
147 150
        }
148 151
        Ok(Self::new(pixels, s))
ombre/src/gfx/image/float.rs +10 -3
69 69
    /// Create a new image from pixels and dimensions.
70 70
    pub fn new(pixels: impl Into<Arc<[f32]>>, size: impl Into<Size<u32>>, channels: u32) -> Self {
71 71
        let size = size.into();
72 72
        let pixels = pixels.into();
73 73
74 -
        assert_eq!(size.area() as usize * channels as usize, pixels.len());
74 +
        assert_eq!(
75 +
            size.w as usize * size.h as usize * channels as usize,
76 +
            pixels.len()
77 +
        );
75 78
        assert!(channels > 0);
76 79
77 80
        Self {
78 81
            size,
79 82
            channels,
149 152
150 153
        if lines == 0 || stride == 0 || channels == 0 {
151 154
            return Err(io::ErrorKind::InvalidData.into());
152 155
        }
153 156
        let size = Size::new(stride, lines);
154 -
        let n = size.area() as usize * channels as usize;
155 -
        let mut pixels = Vec::with_capacity(n);
157 +
        let n = (stride as usize)
158 +
            .checked_mul(lines as usize)
159 +
            .and_then(|n| n.checked_mul(channels as usize))
160 +
            .filter(|&n| n <= isize::MAX as usize / std::mem::size_of::<f32>())
161 +
            .ok_or(io::ErrorKind::InvalidData)?;
162 +
        let mut pixels = Vec::new();
156 163
157 164
        while pixels.len() < n {
158 165
            let value = reader.read_f32_le()?;
159 166
            pixels.push(value);
160 167
        }
syntaxe/src/parsers.rs +55 -22
250 250
            let mut results = vec![item];
251 251
252 252
            // Keep parsing separator plus item pairs.
253 253
            while let Ok((_, rest)) = separator.parse_at(cursor) {
254 254
                let (item, rest) = self.parse_at(rest)?;
255 +
                if rest.input.len() >= cursor.input.len() {
256 +
                    break;
257 +
                }
255 258
256 259
                results.push(item);
257 260
                cursor = rest;
258 261
            }
259 262
            Ok((results, cursor))
384 387
385 388
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
386 389
        let predicate = &self.0;
387 390
388 391
        match cursor.input.chars().next() {
389 -
            Some(c) if predicate(&c) => Ok((c, cursor.advance(c.len_utf8()))),
392 +
            Some(c) if predicate(&c) => Ok((c, cursor.advance(1))),
390 393
            Some(c) => Err(Error::new(ErrorKind::UnexpectedChar(c), cursor)),
391 394
            None => Err(Error::new(ErrorKind::UnexpectedEof, cursor)),
392 395
        }
393 396
    }
394 397
}
399 402
impl<'a> Parser<'a> for Symbol {
400 403
    type Output = char;
401 404
402 405
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
403 406
        match cursor.input.chars().next() {
404 -
            Some(c) if c == self.0 => Ok((c, cursor.advance(c.len_utf8()))),
407 +
            Some(c) if c == self.0 => Ok((c, cursor.advance(1))),
405 408
            _ => Err(Error::new(ErrorKind::ExpectedChar(self.0), cursor)),
406 409
        }
407 410
    }
408 411
}
409 412
419 422
impl<'a> Parser<'a> for Keyword<'a> {
420 423
    type Output = &'a str;
421 424
422 425
    fn parse_at(&self, cursor: Cursor<'a>) -> Result<'a, Self::Output> {
423 426
        match cursor.input.get(..self.0.len()) {
424 -
            Some(word) if word == self.0 => Ok((word, cursor.advance(word.len()))),
427 +
            Some(word) if word == self.0 => Ok((word, cursor.advance(word.chars().count()))),
425 428
            _ => Err(Error::new(ErrorKind::ExpectedString(self.0), cursor)),
426 429
        }
427 430
    }
428 431
}
429 432
541 544
        let mut chars = input.chars();
542 545
        let mut error;
543 546
544 547
        loop {
545 548
            match parser.parse_at(cursor) {
546 -
                Ok((_, _)) => return Ok((&input[..cursor.location.index], cursor)),
549 +
                Ok((_, _)) => return Ok((&input[..input.len() - cursor.input.len()], cursor)),
547 550
                Err(e) => error = e,
548 551
            }
549 -
            if let Some(c) = chars.next() {
550 -
                cursor = cursor.advance(c.len_utf8());
552 +
            if chars.next().is_some() {
553 +
                cursor = cursor.advance(1);
551 554
            } else {
552 555
                break;
553 556
            }
554 557
        }
555 558
        Err(error)
643 646
    fn parse_at(&self, input: Cursor<'a>) -> Result<'a, Self::Output> {
644 647
        let mut input = input;
645 648
        let mut outs = O::default();
646 649
647 650
        while let Ok((out, rest)) = self.0.parse_at(input) {
651 +
            if rest.input.len() >= input.input.len() {
652 +
                break;
653 +
            }
648 654
            outs.extend(std::iter::once(out));
649 655
            input = rest;
650 656
        }
651 657
        Ok((outs, input))
652 658
    }
682 688
        let (out, rest) = parser.parse_at(input)?;
683 689
        outs.extend(std::iter::once(out));
684 690
        input = rest;
685 691
686 692
        while let Ok((out, rest)) = parser.parse_at(input) {
693 +
            if rest.input.len() >= input.input.len() {
694 +
                break;
695 +
            }
687 696
            outs.extend(std::iter::once(out));
688 697
            input = rest;
689 698
        }
690 699
        Ok((outs, input))
691 700
    }
949 958
    move |cursor: Cursor<'a>| -> Result<'a, &'a str> {
950 959
        let input = cursor.input;
951 960
        let (_, mut cursor) = parser.parse_at(cursor)?;
952 961
953 962
        while let Ok((_, rest)) = parser.parse_at(cursor) {
963 +
            if rest.input.len() >= cursor.input.len() {
964 +
                break;
965 +
            }
954 966
            cursor = rest;
955 967
        }
956 968
        let len = input.len() - cursor.input.len();
957 969
958 970
        Ok((&input[..len], cursor))
971 983
/// assert_eq!(parser.parse("abc"), Ok(("", "abc"))); // No match returns empty string
972 984
/// ```
973 985
pub fn take_while<'a, F: Fn(&char) -> bool>(pred: F) -> impl Parser<'a, Output = &'a str> {
974 986
    move |cursor: Cursor<'a>| {
975 987
        let input = cursor.input;
976 -
        let mut len = 0;
988 +
        let count = input.chars().take_while(&pred).count();
989 +
        let rest = cursor.advance(count);
990 +
        let len = input.len() - rest.input.len();
977 991
978 -
        for c in input.chars() {
979 -
            if !pred(&c) {
980 -
                break;
981 -
            }
982 -
            len += c.len_utf8();
983 -
        }
984 -
        Ok((&input[..len], cursor.advance(len)))
992 +
        Ok((&input[..len], rest))
985 993
    }
986 994
}
987 995
988 996
/// Like [`take_while`], but requires at least one matching character.
989 997
/// Parse one or more characters matching a predicate.
1024 1032
pub fn take_until<'a, F: Fn(char) -> bool + Copy + 'static>(
1025 1033
    term: F,
1026 1034
) -> impl Parser<'a, Output = &'a str> {
1027 1035
    move |cursor: Cursor<'a>| {
1028 1036
        let input = cursor.input;
1029 -
        let mut len = 0;
1037 +
        let mut rest = cursor;
1030 1038
1031 1039
        for c in input.chars() {
1032 1040
            if term(c) {
1033 -
                return Ok((&input[..len], cursor.advance(len)));
1041 +
                let len = input.len() - rest.input.len();
1042 +
                return Ok((&input[..len], rest));
1034 1043
            }
1035 -
            len += c.len_utf8();
1044 +
            rest = rest.advance(1);
1036 1045
        }
1037 -
        Err(Error::new(ErrorKind::UnexpectedEof, cursor.advance(len)))
1046 +
        Err(Error::new(ErrorKind::UnexpectedEof, rest))
1038 1047
    }
1039 1048
}
1040 1049
1041 1050
/// Takes the rest of the input as a string slice.
1042 1051
/// Always succeeds.
1047 1056
/// let parser = take_str();
1048 1057
/// assert_eq!(parser.parse("hello world"), Ok(("hello world", "")));
1049 1058
/// assert!(parser.parse("").is_ok());
1050 1059
/// ```
1051 1060
pub fn take_str<'a>() -> impl Parser<'a, Output = &'a str> {
1052 -
    move |cursor: Cursor<'a>| Ok((cursor.input, cursor.advance(cursor.input.len())))
1061 +
    move |cursor: Cursor<'a>| Ok((cursor.input, cursor.advance(cursor.input.chars().count())))
1053 1062
}
1054 1063
1055 1064
/// Takes exactly `n` characters from the input.
1056 1065
/// Fails if there aren't enough characters available.
1057 1066
///
1062 1071
/// assert_eq!(parser.parse("hello world"), Ok(("hello", " world")));
1063 1072
/// assert!(parser.parse("hi").is_err());
1064 1073
/// ```
1065 1074
pub fn take<'a>(n: usize) -> impl Parser<'a, Output = &'a str> {
1066 1075
    move |cursor: Cursor<'a>| {
1067 -
        if cursor.input.len() < n {
1068 -
            return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1076 +
        let mut chars = cursor.input.chars();
1077 +
        for _ in 0..n {
1078 +
            if chars.next().is_none() {
1079 +
                return Err(Error::new(ErrorKind::UnexpectedEof, cursor));
1080 +
            }
1069 1081
        }
1070 -
        Ok((&cursor.input[..n], cursor.advance(n)))
1082 +
        let len = cursor.input.len() - chars.as_str().len();
1083 +
        Ok((&cursor.input[..len], cursor.advance(n)))
1071 1084
    }
1072 1085
}
1073 1086
1074 1087
/// Attempt to parse, and if it fails, backtrack as if no input had been consumed.
1075 1088
///
1106 1119
#[allow(clippy::unwrap_used)]
1107 1120
mod test {
1108 1121
    use super::*;
1109 1122
    use crate::result::Location;
1110 1123
1124 +
    #[test]
1125 +
    fn test_repetition_without_progress() {
1126 +
        let calls = std::cell::Cell::new(0);
1127 +
        let empty = |cursor| {
1128 +
            calls.set(calls.get() + 1);
1129 +
            assert!(
1130 +
                calls.get() <= 8,
1131 +
                "repetition must stop without input progress"
1132 +
            );
1133 +
            Ok(((), cursor))
1134 +
        };
1135 +
        assert_eq!(any::<_, Vec<_>>(&empty).parse("a"), Ok((vec![], "a")));
1136 +
        assert_eq!(many::<_, Vec<_>>(&empty).parse("a"), Ok((vec![()], "a")));
1137 +
        assert_eq!(repeat(&empty).parse("a"), Ok(("", "a")));
1138 +
        assert_eq!(
1139 +
            empty.delimited_by(string("")).parse("a"),
1140 +
            Ok((vec![()], "a"))
1141 +
        );
1142 +
    }
1143 +
1111 1144
    #[test]
1112 1145
    fn test_choice_backtracking() {
1113 1146
        let p = choice([
1114 1147
            string("leave").skip(whitespace()).then(string("england")),
1115 1148
            string("learn").skip(whitespace()).then(string("english")),
syntaxe/src/result.rs +2 -2
54 54
                loc.line += 1;
55 55
                loc.column = 1;
56 56
            } else {
57 57
                loc.column += 1;
58 58
            }
59 -
            loc.index += 1;
59 +
            loc.index += ch.len_utf8();
60 60
        }
61 61
62 62
        Self {
63 -
            input: &self.input[n..],
63 +
            input: chars.as_str(),
64 64
            location: loc,
65 65
        }
66 66
    }
67 67
}
68 68