From 7cf947907d845288c3f9ff790752fc01fcb5b4a5 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Thu, 12 Mar 2020 15:59:45 +0100 Subject: [PATCH] Add to_usize The main benefit of `.to_usize` versus `.into()` is that the type is fixed for the purposes of type-inference. This is handly if you want to do `"hello, world"[..ts.to_usize()]`. --- src/range.rs | 8 ++------ src/size.rs | 17 +++++++++++------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/range.rs b/src/range.rs index c06c19d..ead422c 100644 --- a/src/range.rs +++ b/src/range.rs @@ -127,20 +127,16 @@ impl TextRange { } } -fn ix(size: TextSize) -> usize { - size.into() -} - impl Index 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 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()] } } diff --git a/src/size.rs b/src/size.rs index 867a000..65f5b7e 100644 --- a/src/size.rs +++ b/src/size.rs @@ -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::() < std::mem::size_of::()) as usize] + } + } } /// Methods to act like a primitive integer type, where reasonably applicable. @@ -91,12 +101,7 @@ impl TryFrom for TextSize { impl From for usize { fn from(value: TextSize) -> Self { - assert_lossless_conversion(); - return value.raw as usize; - - const fn assert_lossless_conversion() { - [()][(std::mem::size_of::() < std::mem::size_of::()) as usize] - } + value.to_usize() } }