Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add to_usize #12

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,20 +127,16 @@ impl TextRange {
}
}

fn ix(size: TextSize) -> usize {
size.into()
}

impl Index<TextRange> for str {
type Output = str;
fn index(&self, index: TextRange) -> &Self::Output {
&self[ix(index.start())..ix(index.end())]
&self[index.start().to_usize()..index.end().to_usize()]
}
}

impl IndexMut<TextRange> for str {
fn index_mut(&mut self, index: TextRange) -> &mut Self::Output {
&mut self[ix(index.start())..ix(index.end())]
&mut self[index.start().to_usize()..index.end().to_usize()]
}
}

Expand Down
17 changes: 11 additions & 6 deletions src/size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ impl TextSize {
pub const fn zero() -> TextSize {
TextSize(0)
}

/// Cast to `usize`.
pub const fn to_usize(self) -> usize {
assert_lossless_conversion();
return self.raw as usize;

const fn assert_lossless_conversion() {
[()][(std::mem::size_of::<usize>() < std::mem::size_of::<u32>()) as usize]
}
}
}

/// Methods to act like a primitive integer type, where reasonably applicable.
Expand Down Expand Up @@ -91,12 +101,7 @@ impl TryFrom<usize> for TextSize {

impl From<TextSize> for usize {
fn from(value: TextSize) -> Self {
assert_lossless_conversion();
return value.raw as usize;

const fn assert_lossless_conversion() {
[()][(std::mem::size_of::<usize>() < std::mem::size_of::<u32>()) as usize]
}
value.to_usize()
}
}

Expand Down