LineNumber

Struct LineNumber 

Source
pub struct LineNumber {
    pub number: NonZeroUsize,
}
Expand description

A 1-based line number, as used in most text editors

This is used for exchanging with the user, and for most APIs. Disambiguation is done by using either LineNumber or LineIndex.

Fields§

§number: NonZeroUsize

Implementations§

Source§

impl LineNumber

Source

pub fn new(number: usize) -> Option<Self>

Source

pub fn to_index(&self) -> LineIndex

Examples found in repository?
examples/sort-all-enums/main.rs (line 145)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}
Source

pub fn from_index(index: LineIndex) -> Self

Examples found in repository?
examples/sort-all-enums/main.rs (line 141)
86fn main() -> CsResult<()> {
87    let start = std::time::Instant::now();
88    let args = Args::parse();
89    let files = get_all_rust_files(args.path, &args.include, &args.exclude)?;
90    eprintln!("Found {} rust files", files.len());
91    let mut sorted_enum_count = 0;
92    let mut ok_files_count = 0;
93    let mut invalid_files_count = 0;
94    let mut incomplete_files_count = 0;
95    let mut excluded_enums_count = 0;
96    let mut modified_files_count = 0;
97    let mut empty_files_count = 0;
98    for file in &files {
99        let loc_list = LocList::read_file(file, Language::Rust);
100        let mut loc_list = match loc_list {
101            Ok(loc_list) => loc_list,
102            Err(e) => {
103                eprintln!("{} in {}: {:?}", "ERROR".red(), file.display(), e);
104                invalid_files_count += 1;
105                continue;
106            }
107        };
108        if !loc_list.has_content() {
109            empty_files_count += 1;
110            continue;
111        }
112        if !loc_list.is_complete() {
113            eprintln!(
114                "skipping {} ({})",
115                file.display(),
116                "not consistent enough".yellow()
117            );
118            incomplete_files_count += 1;
119            continue;
120        }
121        let mut modified = false;
122        let mut line_idx = 0;
123        ok_files_count += 1;
124        while line_idx + 2 < loc_list.len() {
125            let loc = &loc_list.locs[line_idx];
126            if !loc.starts_normal {
127                line_idx += 1;
128                continue;
129            }
130            let content = &loc.content;
131            let Some((_, name)) =
132                regex_captures!(r"^[\s\w()]*\benum\s+([^({]+)\s+\{\s**$", content)
133            else {
134                line_idx += 1;
135                continue;
136            };
137
138            // We look whether the annotations before the enum contain any one
139            // of the excluding keywords
140            let whole_enum_range = loc_list
141                .block_range_of_line_number(LineNumber::from_index(line_idx))
142                .unwrap();
143            let whole_enum_range = loc_list.trimmed_range(whole_enum_range);
144            let excluding_keyword = EXCLUDING_KEYWORDS.iter().find(|&keyword| {
145                loc_list.locs[whole_enum_range.start.to_index()..line_idx]
146                    .iter()
147                    .any(|loc| loc.sort_key.contains(keyword))
148            });
149            if let Some(excluding_keyword) = excluding_keyword {
150                eprintln!("skipping enum {} ({})", name, excluding_keyword.yellow());
151                excluded_enums_count += 1;
152                line_idx = whole_enum_range.end.to_index() + 1;
153                continue;
154            }
155            loc_list.print_range_debug(
156                &format!(" sorting enum {} ", name.blue()),
157                whole_enum_range,
158            );
159            let range = loc_list.range_around_line_index(line_idx + 1).unwrap();
160            loc_list.sort_range(range).unwrap();
161            line_idx = range.end.to_index() + 2;
162            sorted_enum_count += 1;
163            modified = true;
164        }
165        if modified {
166            loc_list.write_file(file)?;
167            eprintln!("wrote {}", file.display());
168            modified_files_count += 1;
169        }
170    }
171    eprintln!("\nDone in {:.3}s\n", start.elapsed().as_secs_f32());
172    eprintln!("I analyzed {} files", files.len());
173    let mut problems = Vec::new();
174    if empty_files_count > 0 {
175        problems.push(format!("{} empty files", empty_files_count));
176    }
177    if incomplete_files_count > 0 {
178        problems.push(format!("{} incomplete files", incomplete_files_count));
179    }
180    if invalid_files_count > 0 {
181        problems.push(format!("{} invalid files", invalid_files_count));
182    }
183    if problems.is_empty() {
184        eprintln!("All {} files were ok", ok_files_count);
185    } else {
186        eprintln!(
187            "{} files were OK but I encountered {}",
188            ok_files_count,
189            problems.join(", ")
190        );
191    }
192    if excluded_enums_count > 0 {
193        eprintln!(
194            "I excluded {} enums whose annotation contained excluding keywords",
195            excluded_enums_count
196        );
197    }
198    eprintln!(
199        "I sorted {} enums in {} files",
200        sorted_enum_count, modified_files_count
201    );
202    Ok(())
203}

Trait Implementations§

Source§

impl Clone for LineNumber

Source§

fn clone(&self) -> LineNumber

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for LineNumber

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for LineNumber

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl FromStr for LineNumber

Source§

type Err = ParseIntError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Ord for LineNumber

Source§

fn cmp(&self, other: &LineNumber) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for LineNumber

Source§

fn eq(&self, other: &LineNumber) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for LineNumber

Source§

fn partial_cmp(&self, other: &LineNumber) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Copy for LineNumber

Source§

impl Eq for LineNumber

Source§

impl StructuralPartialEq for LineNumber

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.