Skip to content

Commit 8854e07

Browse files
authored
Merge pull request rust-analyzer/smol_str#19 from Dr-Emann/limit_substr_check
Avoid checking long strings for matching against whitespace
2 parents a39f3aa + 3759186 commit 8854e07

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

src/tools/rust-analyzer/lib/smol_str/src/lib.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
use std::{borrow::Borrow, cmp::Ordering, fmt, hash, iter, ops::Deref, sync::Arc};
1+
use std::{
2+
borrow::Borrow,
3+
cmp::{self, Ordering},
4+
fmt, hash, iter,
5+
ops::Deref,
6+
sync::Arc,
7+
};
28

39
/// A `SmolStr` is a string type that has the following properties:
410
///
@@ -368,10 +374,17 @@ impl Repr {
368374
};
369375
}
370376

371-
let newlines = text.bytes().take_while(|&b| b == b'\n').count();
372-
if text[newlines..].bytes().all(|b| b == b' ') {
373-
let spaces = len - newlines;
374-
if newlines <= N_NEWLINES && spaces <= N_SPACES {
377+
if len <= N_NEWLINES + N_SPACES {
378+
let bytes = text.as_bytes();
379+
let possible_newline_count = cmp::min(len, N_NEWLINES);
380+
let newlines = bytes[..possible_newline_count]
381+
.iter()
382+
.take_while(|&&b| b == b'\n')
383+
.count();
384+
let possible_space_count = len - newlines;
385+
if possible_space_count <= N_SPACES && bytes[newlines..].iter().all(|&b| b == b' ')
386+
{
387+
let spaces = possible_space_count;
375388
return Repr::Substring { newlines, spaces };
376389
}
377390
}
@@ -420,9 +433,9 @@ impl Repr {
420433

421434
#[cfg(feature = "serde")]
422435
mod serde {
436+
use super::SmolStr;
423437
use ::serde::de::{Deserializer, Error, Unexpected, Visitor};
424438
use std::fmt;
425-
use super::SmolStr;
426439

427440
// https://github.com/serde-rs/serde/blob/629802f2abfd1a54a6072992888fea7ca5bc209f/serde/src/private/de.rs#L56-L125
428441
fn smol_str<'de: 'a, 'a, D>(deserializer: D) -> Result<SmolStr, D::Error>

src/tools/rust-analyzer/lib/smol_str/tests/test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ proptest! {
8787
#[cfg(feature = "serde")]
8888
mod serde_tests {
8989
use super::*;
90-
use serde::{Serialize, Deserialize};
90+
use serde::{Deserialize, Serialize};
9191
use std::collections::HashMap;
9292

9393
#[derive(Serialize, Deserialize)]

0 commit comments

Comments
 (0)