fix: a logic error in Step (#233)

This commit is contained in:
Nguyễn Đức Toàn 2023-10-01 08:42:56 +07:00 committed by sxyazi
parent 5584ba4844
commit a5aa9cb817
No known key found for this signature in database
2 changed files with 14 additions and 14 deletions

View File

@ -106,9 +106,9 @@ impl Folder {
pub fn hover(&mut self, url: &Url) -> bool { pub fn hover(&mut self, url: &Url) -> bool {
let new = self.files.position(url).unwrap_or(self.cursor); let new = self.files.position(url).unwrap_or(self.cursor);
if new > self.cursor { if new > self.cursor {
self.next(Step::from(new - self.cursor)) self.next(Step::next(new - self.cursor))
} else { } else {
self.prev(Step::from(self.cursor - new)) self.prev(Step::prev(self.cursor - new))
} }
} }

View File

@ -1,5 +1,6 @@
use std::{num::ParseIntError, str::FromStr}; use std::{num::ParseIntError, str::FromStr};
#[derive(Clone, Copy)]
pub enum Step { pub enum Step {
Fixed(isize), Fixed(isize),
Percent(i8), Percent(i8),
@ -25,29 +26,28 @@ impl From<isize> for Step {
fn from(n: isize) -> Self { Self::Fixed(n) } fn from(n: isize) -> Self { Self::Fixed(n) }
} }
impl From<usize> for Step { impl Step {
fn from(n: usize) -> Self { Self::Fixed(n as isize) } #[inline]
pub fn prev(n: usize) -> Self { Self::Fixed(-(n as isize)) }
#[inline]
pub fn next(n: usize) -> Self { Self::Fixed(n as isize) }
} }
impl Step { impl Step {
#[inline] #[inline]
fn fixed<F: FnOnce() -> usize>(self, f: F) -> isize { pub fn add<F: FnOnce() -> usize>(self, pos: usize, f: F) -> usize {
match self { let fixed = match self {
Self::Fixed(n) => n, Self::Fixed(n) => n,
Self::Percent(0) => 0, Self::Percent(0) => 0,
Self::Percent(n) => n as isize * f() as isize / 100, Self::Percent(n) => n as isize * f() as isize / 100,
} };
}
#[inline]
pub fn add<F: FnOnce() -> usize>(self, pos: usize, f: F) -> usize {
let fixed = self.fixed(f);
if fixed > 0 { pos + fixed as usize } else { pos.saturating_sub(fixed.unsigned_abs()) } if fixed > 0 { pos + fixed as usize } else { pos.saturating_sub(fixed.unsigned_abs()) }
} }
#[inline] #[inline]
pub fn is_positive(&self) -> bool { pub fn is_positive(self) -> bool {
match *self { match self {
Self::Fixed(n) => n > 0, Self::Fixed(n) => n > 0,
Self::Percent(n) => n > 0, Self::Percent(n) => n > 0,
} }