### Accessing Metadata with Result Handling Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Shows how to use `Result` to handle potential errors when accessing file metadata. The example attempts to get metadata for the root directory and a non-existent path, demonstrating success and failure cases. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### RopeBuilder Example Usage in Rust Source: https://docs.rs/ropey/1.6.1/ropey/struct.RopeBuilder Demonstrates how to use the RopeBuilder to construct a Rope from multiple string chunks. It shows the pattern of creating a builder, appending chunks, and finally finishing the build to obtain the Rope object. ```rust let mut builder = RopeBuilder::new(); builder.append("Hello "); builder.append("world!\n"); builder.append("How's "); builder.append("it goin"); builder.append("g?"); let rope = builder.finish(); assert_eq!(rope, "Hello world!\nHow's it going?"); ``` -------------------------------- ### Rust Result unwrap() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Demonstrates the basic usage of the unwrap() method on a Result type. It shows how to extract the Ok value and how it panics when called on an Err variant, providing the error message. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### Rust Result into_ok() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Illustrates the experimental into_ok() method, which safely returns the Ok value without panicking. This method is designed for Result types where the error variant is impossible to construct. ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` -------------------------------- ### Rust Ropey Lines Iterator Example Usage Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Lines Demonstrates using the `reversed` iterator method to enumerate lines of a Rope in reverse order, starting from the end of the Rope. ```Rust // Enumerate the rope's lines in reverse, starting from the end. for (i, line) in rope.lines_at(rope.len_lines()).reversed().enumerate() { println!("{} {}", i, line); } ``` -------------------------------- ### Rust Result and() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Shows the usage of the and() method, which returns the second Result if the first is Ok, otherwise returns the first Result's Err. Arguments are evaluated eagerly. ```rust let x: Result = Ok(2); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("late error")); let x: Result = Err("early error"); let y: Result<&str, &str> = Ok("foo"); assert_eq!(x.and(y), Err("early error")); let x: Result = Err("not a 2"); let y: Result<&str, &str> = Err("late error"); assert_eq!(x.and(y), Err("not a 2")); let x: Result = Ok(2); let y: Result<&str, &str> = Ok("different result type"); assert_eq!(x.and(y), Ok("different result type")); ``` -------------------------------- ### RopeSlice Length Methods Source: https://docs.rs/ropey/1.6.1/ropey/struct.RopeSlice Provides methods to get the length of the RopeSlice in bytes, characters, lines, and UTF-16 code units. ```APIDOC ## RopeSlice An immutable view into part of a `Rope`. All indexing is relative to the start of their range, and all iterators and methods that return text truncate that text to the range of the slice. ### Methods #### `len_bytes(&self) -> usize` - **Description**: Total number of bytes in the `RopeSlice`. - **Time Complexity**: O(1) #### `len_chars(&self) -> usize` - **Description**: Total number of characters in the `RopeSlice`. - **Time Complexity**: O(1) #### `len_lines(&self) -> usize` - **Description**: Total number of lines in the `RopeSlice`. - **Time Complexity**: O(1) #### `len_utf16_cu(&self) -> usize` - **Description**: Total number of UTF-16 code units that would be in the `RopeSlice` if it were encoded as UTF-16. - **Time Complexity**: O(1) ``` -------------------------------- ### Rope: Get Byte, Character, and Line Counts Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Provides methods to efficiently retrieve the total number of bytes, characters, and lines within a Rope. These operations run in O(1) time. ```rust let rope = Rope::from_str("Hello\nWorld"); assert_eq!(rope.len_bytes(), 12); assert_eq!(rope.len_chars(), 11); assert_eq!(rope.len_lines(), 2); ``` -------------------------------- ### Get Byte Index of Line Start (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Retrieves the byte index corresponding to the beginning of a specified line in the Rope. Supports line indices up to one-past-the-end. Panics if the line index is out of bounds. Operates in O(log N) time. ```rust pub fn line_to_byte(&self, line_idx: usize) -> usize ``` -------------------------------- ### Reimplementing byte_to_char using Ropey Low-Level APIs in Rust Source: https://docs.rs/ropey/1.6.1/ropey/index Illustrates how to reimplement the `Rope::byte_to_char()` method using Ropey's low-level chunk-fetching and utility functions. This example shows accessing internal string chunks and using `str_utils::byte_to_char_idx` for efficient index conversion. ```rust use ropey::{ Rope, str_utils::byte_to_char_idx }; fn byte_to_char(rope: &Rope, byte_idx: usize) -> usize { let (chunk, b, c, _) = rope.chunk_at_byte(byte_idx); c + byte_to_char_idx(chunk, byte_idx - b) } ``` -------------------------------- ### Rust Result and_then() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Demonstrates the and_then() method, which calls a closure with the Ok value if the Result is Ok, otherwise returns the Err. This is useful for chaining operations that return Result types and provides lazy evaluation. ```rust let result1: Result = Ok(10); let result2 = result1.and_then(|val| Ok(val * 2)); // result2 is Ok(20) let result3: Result = Err("Something went wrong"); let result4 = result3.and_then(|val| Ok(val * 2)); // result4 is Err("Something went wrong") ``` -------------------------------- ### Rust Result into_err() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Demonstrates the experimental into_err() method, which safely returns the Err value without panicking. This is useful for Result types where the Ok variant is impossible. ```rust fn only_bad_news() -> Result { Err("Oops, it failed".into()) } let error: String = only_bad_news().into_err(); println!("{error}"); ``` -------------------------------- ### Generic Blanket Implementations Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Chars Documentation for generic blanket implementations, such as `Any` and `Borrow`, applicable to various types. ```APIDOC ## Generic Blanket Implementations ### Description Provides documentation for blanket implementations that apply to many types, such as trait objects and borrowing capabilities. ### Implemented Traits - `Any` - `type_id(&self) -> TypeId`: Gets the `TypeId` of `self`. - `Borrow` - `borrow(&self) -> &T`: Immutably borrows from an owned value. - `BorrowMut` - `borrow_mut(&mut self) -> &mut T`: Mutably borrows from an owned value. - `CloneToUninit` (Nightly-only) - `clone_to_uninit(&self, dest: *mut u8)`: Performs copy-assignment from `self` to `dest`. ### Request Example ```json { "example": "Not applicable as these are trait implementations, not API endpoints." } ``` ### Response #### Success Response (200) - Describes the methods available through these blanket implementations. ### Response Example ```json { "example": "Details methods like type_id, borrow, borrow_mut, and clone_to_uninit that are available based on these blanket implementations." } ``` ``` -------------------------------- ### Iterating over Rope Characters in Reverse Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Chars This example demonstrates how to use the `reversed()` method of the `Chars` iterator to iterate over the characters of a Rope in reverse order, starting from the end. It also shows how to combine this with `enumerate()` to get the index of each character. ```rust // Enumerate the rope's chars in reverse, starting from the end. for (i, ch) in rope.chars_at(rope.len_chars()).reversed().enumerate() { println!("{} {}", i, ch); } ``` -------------------------------- ### Rope: Get chunks iterator at byte index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns an Option containing a tuple with a Chunks iterator, start byte, end byte, and length, starting from the specified byte index. Returns None if the index is invalid. ```rust pub fn get_chunks_at_byte( &self, byte_idx: usize, ) -> Option<(Chunks<'_>, usize, usize, usize)> ``` -------------------------------- ### Rope: Get chunks iterator at char index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Safely retrieves an Option containing a tuple with a Chunks iterator, start char, end char, and length, starting from the specified character index. Returns None for invalid indices. ```rust pub fn get_chunks_at_char( &self, char_idx: usize, ) -> Option<(Chunks<'_>, usize, usize, usize)> ``` -------------------------------- ### Rope Trait Implementations Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Documentation for various trait implementations for the Rope data structure, including Clone, Debug, Default, Display, and multiple From conversions. ```APIDOC ## Rope Trait Implementations ### `impl Clone for Rope` #### `clone` **Description**: Returns a duplicate of the `Rope` value. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: None #### `clone_from` **Description**: Performs copy-assignment from a source `Rope`. **Method**: POST (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **source** (&Self) - Required - The source Rope to copy from. ### `impl Debug for Rope` #### `fmt` **Description**: Formats the `Rope` value using the given formatter. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **f** (&mut Formatter<'_>) - Required - The formatter to use. ### `impl Default for Rope` #### `default` **Description**: Returns the default value for a `Rope`, typically an empty Rope. **Method**: GET (conceptual) **Endpoint**: N/A (Static Method) **Parameters**: None #### Success Response (200) - **Self** - An empty Rope. ### `impl Display for Rope` #### `fmt` **Description**: Formats the `Rope` value as a displayable string using the given formatter. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **f** (&mut Formatter<'_>) - Required - The formatter to use. ### `impl<'a> From<&'a Rope> for Cow<'a, str>` #### `from` **Description**: Attempts to borrow the contents of the `Rope` as a `Cow<'a, str>`, converting to an owned string if the contents are not contiguous. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **r** (&'a Rope) - Required - The Rope to convert. #### Success Response (200) - **Self** - A `Cow<'a, str>` representing the Rope's content. ### `impl<'a> From<&'a Rope> for String` #### `from` **Description**: Converts a `Rope` reference into an owned `String`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **r** (&'a Rope) - Required - The Rope to convert. #### Success Response (200) - **Self** - An owned `String`. ### `impl<'a> From<&'a str> for Rope` #### `from` **Description**: Converts a string slice (`&'a str`) into a `Rope`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **text** (&'a str) - Required - The string slice to convert. #### Success Response (200) - **Self** - A `Rope` created from the string slice. ### `impl<'a> From> for Rope` #### `from` **Description**: Converts a `Cow<'a, str>` into a `Rope`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **text** (Cow<'a, str>) - Required - The Cow to convert. #### Success Response (200) - **Self** - A `Rope` created from the Cow. ### `impl<'a> From for Cow<'a, str>` #### `from` **Description**: Converts an owned `Rope` into a `Cow<'a, str>`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **r** (Rope) - Required - The Rope to convert. #### Success Response (200) - **Self** - A `Cow<'a, str>` representing the Rope's content. ### `impl From for String` #### `from` **Description**: Converts an owned `Rope` into an owned `String`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **r** (Rope) - Required - The Rope to convert. #### Success Response (200) - **Self** - An owned `String`. ### `impl<'a> From> for Rope` #### `from` **Description**: Converts a `RopeSlice` into a `Rope`, sharing data where possible. Runs in O(log N) time. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **s** (RopeSlice<'a>) - Required - The RopeSlice to convert. #### Success Response (200) - **Self** - A `Rope` created from the RopeSlice. ### `impl From for Rope` #### `from` **Description**: Converts an owned `String` into a `Rope`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **text** (String) - Required - The String to convert. #### Success Response (200) - **Self** - A `Rope` created from the String. ### `impl<'a> FromIterator<&'a str> for Rope` #### `from_iter` **Description**: Creates a `Rope` from an iterator of string slices (`&'a str`). **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **iter** (T: IntoIterator) - Required - An iterator yielding string slices. #### Success Response (200) - **Self** - A `Rope` created from the iterator. ### `impl<'a> FromIterator> for Rope` #### `from_iter` **Description**: Creates a `Rope` from an iterator of `Cow<'a, str>`. **Method**: GET (conceptual) **Endpoint**: N/A (Conversion Function) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body - **iter** (T: IntoIterator>) - Required - An iterator yielding `Cow<'a, str>`. #### Success Response (200) - **Self** - A `Rope` created from the iterator. ``` -------------------------------- ### Rope: Get chunks iterator at line break index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Provides an Option containing a tuple with a Chunks iterator, start index, end index, and length, starting from the specified line break index. Returns None if the index is out of bounds. ```rust pub fn get_chunks_at_line_break( &self, line_break_idx: usize, ) -> Option<(Chunks<'_>, usize, usize, usize)> ``` -------------------------------- ### RopeBuilder API Source: https://docs.rs/ropey/1.6.1/ropey/struct.RopeBuilder Provides methods for creating, appending to, and finishing the construction of a Rope using RopeBuilder. ```APIDOC ## Struct RopeBuilder ### Description An efficient incremental `Rope` builder. This is used to efficiently build ropes from sequences of text chunks. ### Methods #### `new()` Creates a new RopeBuilder, ready for input. - **Method:** `pub fn new() -> Self` #### `append(chunk: &str)` Appends `chunk` to the end of the in-progress `Rope`. Call this method repeatedly to incrementally build up a `Rope`. The passed text chunk can be as large or small as desired, but larger chunks are more efficient. `chunk` must be valid utf8 text. - **Method:** `pub fn append(&mut self, chunk: &str)` - **Parameters:** - `chunk` (str) - Required - The text chunk to append. #### `finish()` Finishes the build, and returns the `Rope`. Note: this method consumes the builder. If you want to continue building other ropes with the same prefix, you can clone the builder before calling `finish()`. - **Method:** `pub fn finish(self) -> Rope` ### Example ```rust let mut builder = RopeBuilder::new(); builder.append("Hello "); builder.append("world!\n"); builder.append("How's "); builder.append("it goin"); builder.append("g?"); let rope = builder.finish(); assert_eq!(rope, "Hello world!\nHow's it going?"); ``` ### Implementations #### `Clone` for `RopeBuilder` ```rust impl Clone for RopeBuilder ``` #### `Debug` for `RopeBuilder` ```rust impl Debug for RopeBuilder ``` #### `Default` for `RopeBuilder` ```rust impl Default for RopeBuilder ``` ``` -------------------------------- ### Rope: Get chars iterator at index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Provides an Option containing a Chars iterator starting from the specified character index. Returns None if the index is invalid. ```rust pub fn get_chars_at(&self, char_idx: usize) -> Option> ``` -------------------------------- ### Rope: Get bytes iterator at index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns an Option containing a Bytes iterator starting from the specified byte index. Returns None if the index is out of bounds. ```rust pub fn get_bytes_at(&self, byte_idx: usize) -> Option> ``` -------------------------------- ### Result Methods Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Documentation for common Result type methods. ```APIDOC ## GET /result/unwrap ### Description Retrieves the contained `Ok` value or panics if the value is an `Err`. ### Method GET ### Endpoint /result/unwrap ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value to unwrap. ### Request Example ```json { "value": "Ok(2)" } ``` ### Response #### Success Response (200) - **T** (type) - The contained Ok value. #### Response Example ```json { "value": 2 } ``` ## GET /result/unwrap_or_default ### Description Returns the contained `Ok` value or a default value if the Result is an `Err`. ### Method GET ### Endpoint /result/unwrap_or_default ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value. ### Request Example ```json { "value": "Ok(2)" } ``` ### Response #### Success Response (200) - **T** (type) - The contained Ok value or the default value for the type. #### Response Example ```json { "value": 2 } ``` ## GET /result/expect_err ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`. ### Method GET ### Endpoint /result/expect_err ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value. - **msg** (string) - Required - The panic message. ### Request Example ```json { "value": "Ok(10)", "msg": "Testing expect_err" } ``` ### Response #### Success Response (200) - **E** (type) - The contained Err value. #### Response Example ```json { "error": "Testing expect_err: 10" } ``` ## GET /result/unwrap_err ### Description Returns the contained `Err` value, consuming the `self` value. Panics if the value is an `Ok`. ### Method GET ### Endpoint /result/unwrap_err ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value. ### Request Example ```json { "value": "Err(\"emergency failure\")" } ``` ### Response #### Success Response (200) - **E** (type) - The contained Err value. #### Response Example ```json { "error": "emergency failure" } ``` ## GET /result/into_ok ### Description Returns the contained `Ok` value, but never panics. This is an experimental API. ### Method GET ### Endpoint /result/into_ok ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value. ### Request Example ```json { "value": "Ok(\"success\")" } ``` ### Response #### Success Response (200) - **T** (type) - The contained Ok value. #### Response Example ```json { "value": "success" } ``` ## GET /result/into_err ### Description Returns the contained `Err` value, but never panics. This is an experimental API. ### Method GET ### Endpoint /result/into_err ### Parameters #### Query Parameters - **value** (Result) - Required - The Result value. ### Request Example ```json { "value": "Err(\"failure\")" } ``` ### Response #### Success Response (200) - **E** (type) - The contained Err value. #### Response Example ```json { "error": "failure" } ``` ## GET /result/and ### Description Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`. Arguments are eagerly evaluated. ### Method GET ### Endpoint /result/and ### Parameters #### Query Parameters - **self_value** (Result) - Required - The first Result value. - **res_value** (Result) - Required - The second Result value. ### Request Example ```json { "self_value": "Ok(2)", "res_value": "Ok(\"different result type\")" } ``` ### Response #### Success Response (200) - **Result** (type) - The resulting Result value. #### Response Example ```json { "value": "different result type" } ``` ## GET /result/and_then ### Description Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`. This function can be used for control flow based on `Result` values. ### Method GET ### Endpoint /result/and_then ### Parameters #### Query Parameters - **self_value** (Result) - Required - The first Result value. - **op** (function) - Required - A function that takes T and returns Result. ### Request Example ```json { "self_value": "Ok(2)", "op": "(x) => Ok(x * 2)" } ``` ### Response #### Success Response (200) - **Result** (type) - The resulting Result value. #### Response Example ```json { "value": 4 } ``` ``` -------------------------------- ### By Reference Adapter Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Lines Creates a reference to the iterator. ```APIDOC ## By Reference Iterator Adapter ### `by_ref(&mut self)` Creates a “by reference” adapter for this instance of `Iterator`. - **Method**: `by_ref` - **Returns**: `&mut Self` ``` -------------------------------- ### Get Chunk at Line Break Index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns the chunk of text containing the specified line break index, along with the byte and character indices of the chunk's start and its line index. Considers the start and end of the rope as line breaks. Panics if the line break index is out of bounds. Operates in O(log N) time. ```rust pub fn chunk_at_line_break(&self, line_break_idx: usize) -> (&str, usize, usize, usize) ``` -------------------------------- ### Rope: Get lines iterator at index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Safely retrieves an Option containing a Lines iterator starting from the specified line index. Returns None if the index is out of bounds. ```rust pub fn get_lines_at(&self, line_idx: usize) -> Option> ``` -------------------------------- ### Rust Chunks Iterator Example Usage Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Chunks Demonstrates how to use the `reversed()` method of the `Chunks` iterator in conjunction with `enumerate()` to process rope chunks in reverse order, starting from the end of the rope. ```Rust // Enumerate the rope's chunks in reverse, starting from the end. for (i, chunk) in rope.chunks_at_byte(rope.len_bytes()).0.reversed().enumerate() { println!("{} {}", i, chunk); } ``` -------------------------------- ### Rope: Execute Query Operations (Length and Indexing) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Illustrates how to query a Rope for its length in bytes, characters, and lines, as well as converting line numbers to character indices. These queries are O(1). ```rust let rope = Rope::from_str("Hello みんなさん!\nHow are you?\nThis text has multiple lines!"); assert_eq!(rope.len_bytes(), 70); assert_eq!(rope.len_chars(), 58); assert_eq!(rope.len_lines(), 3); assert_eq!(rope.line_to_char(0), 0); assert_eq!(rope.line_to_char(1), 13); assert_eq!(rope.line_to_char(2), 26); ``` -------------------------------- ### RopeSlice Index Conversion Methods Source: https://docs.rs/ropey/1.6.1/ropey/struct.RopeSlice Provides methods to convert between different indexing schemes (byte, char, line, UTF-16 code units) within a RopeSlice. ```APIDOC ## RopeSlice Index Conversion These methods allow conversion between byte, character, line, and UTF-16 code unit indices within a `RopeSlice`. ### Methods #### `byte_to_char(&self, byte_idx: usize) -> usize` - **Description**: Returns the character index of the given byte index. - If the byte is in the middle of a multi-byte char, returns the index of the char that the byte belongs to. - `byte_idx` can be one-past-the-end, which will return one-past-the-end char index. - **Time Complexity**: O(log N) - **Panics**: Panics if `byte_idx` is out of bounds (`byte_idx > len_bytes()`). #### `byte_to_line(&self, byte_idx: usize) -> usize` - **Description**: Returns the line index of the given byte index. - Lines are zero-indexed. - `byte_idx` can be one-past-the-end, which will return the last line index. - **Time Complexity**: O(log N) - **Panics**: Panics if `byte_idx` is out of bounds (`byte_idx > len_bytes()`). #### `char_to_byte(&self, char_idx: usize) -> usize` - **Description**: Returns the byte index of the given character index. - `char_idx` can be one-past-the-end, which will return one-past-the-end byte index. - **Time Complexity**: O(log N) - **Panics**: Panics if `char_idx` is out of bounds (`char_idx > len_chars()`). #### `char_to_line(&self, char_idx: usize) -> usize` - **Description**: Returns the line index of the given character index. - Lines are zero-indexed. - `char_idx` can be one-past-the-end, which will return one-past-the-end char index. - **Time Complexity**: O(log N) - **Panics**: Panics if `char_idx` is out of bounds (`char_idx > len_chars()`). #### `char_to_utf16_cu(&self, char_idx: usize) -> usize` - **Description**: Returns the UTF-16 code unit index of the given character index. - **Time Complexity**: O(log N) - **Panics**: Panics if `char_idx` is out of bounds (`char_idx > len_chars()`). #### `utf16_cu_to_char(&self, utf16_cu_idx: usize) -> usize` - **Description**: Returns the character index of the given UTF-16 code unit index. - If the UTF-16 code unit is in the middle of a char, returns the index of the char that it belongs to. - **Time Complexity**: O(log N) - **Panics**: Panics if `utf16_cu_idx` is out of bounds (`utf16_cu_idx > len_utf16_cu()`). #### `line_to_byte(&self, line_idx: usize) -> usize` - **Description**: Returns the byte index of the start of the given line index. - Lines are zero-indexed. - `line_idx` can be one-past-the-end, which will return one-past-the-end byte index. - **Time Complexity**: O(log N) - **Panics**: Panics if `line_idx` is out of bounds (`line_idx > len_lines()`). #### `line_to_char(&self, line_idx: usize) -> usize` - **Description**: Returns the character index of the start of the given line index. - Lines are zero-indexed. - `line_idx` can be one-past-the-end, which will return one-past-the-end char index. - **Time Complexity**: O(log N) - **Panics**: Panics if `line_idx` is out of bounds (`line_idx > len_lines()`). #### `byte(&self, byte_idx: usize) -> u8` - **Description**: Returns the byte at the specified byte index. - **Time Complexity**: O(log N) - **Panics**: Panics if `byte_idx` is out of bounds (`byte_idx >= len_bytes()`). ``` -------------------------------- ### Rust Result unwrap_or_default() Example Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Illustrates the use of unwrap_or_default() to get the contained Ok value or a default value if the Result is Err. This is useful for parsing strings into numbers where invalid input should default to zero. ```rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Rope: Get chunk at char index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Safely returns details of the chunk containing a given character index. The result is an Option tuple with the string slice, start char, end char, and length, or None. ```rust pub fn get_chunk_at_char( &self, char_idx: usize, ) -> Option<(&str, usize, usize, usize)> ``` -------------------------------- ### Rope: Get chunk at line break index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Retrieves information about the chunk associated with a line break index. Returns an Option tuple containing the string slice, start index, end index, and length, or None. ```rust pub fn get_chunk_at_line_break( &self, line_break_idx: usize, ) -> Option<(&str, usize, usize, usize)> ``` -------------------------------- ### Blanket Implementations Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Bytes Documentation for blanket implementations, such as the 'Any' and 'Borrow' traits. ```APIDOC ## GET /blanket_implementations/{trait_name} ### Description Provides details about blanket implementations for a specified trait. ### Method GET ### Endpoint /blanket_implementations/{trait_name} ### Parameters #### Path Parameters - **trait_name** (string) - Required - The name of the trait to get information about (e.g., 'Any', 'Borrow', 'BorrowMut', 'CloneToUninit'). ### Response #### Success Response (200) - **trait_name** (string) - The name of the trait. - **description** (string) - A description of the blanket implementation. - **methods** (array) - An array of available methods for the trait. - **name** (string) - The name of the method. - **description** (string) - A description of the method. - **source** (string) - Link to the source code. #### Response Example ```json { "trait_name": "Any", "description": "Blanket implementation for the Any trait.", "methods": [ { "name": "type_id", "description": "Gets the TypeId of self.", "source": "Source§" } ] } ``` ``` -------------------------------- ### Get Character Index of Line Start (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Retrieves the character index corresponding to the beginning of a specified line in the Rope. Supports line indices up to one-past-the-end. Panics if the line index is out of bounds. Operates in O(log N) time. ```rust pub fn line_to_char(&self, line_idx: usize) -> usize ``` -------------------------------- ### Converting Result to Option with ok() Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Shows how the `ok()` method converts a `Result` into an `Option`, consuming the `Result` and discarding any error value. It returns `Some(T)` if the `Result` was `Ok`, and `None` otherwise. ```rust let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` -------------------------------- ### Rope: Define and Initialize a Rope Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Defines the Rope struct for UTF-8 text and provides methods for initialization from string slices or readers. Operations are generally O(log N). ```rust pub struct Rope { /* private fields */ } impl Rope { pub fn new() -> Self pub fn from_str(text: &str) -> Self // pub fn from_reader(reader: T) -> Result } ``` -------------------------------- ### Basic Ropey Text File Manipulation in Rust Source: https://docs.rs/ropey/1.6.1/ropey/index Demonstrates loading a text file into a Rope, performing line-based edits (removal and insertion), and saving the modified content back to disk. It utilizes Rust's standard library for file I/O and the ropey crate for text manipulation. ```rust use std::fs::File; use std::io::{BufReader, BufWriter}; use ropey::Rope; // Load a text file. let mut text = Rope::from_reader( BufReader::new(File::open("my_great_book.txt")?) )?; // Print the 516th line (zero-indexed) to see the terrible // writing. println!("{}", text.line(515)); // Get the start/end char indices of the line. let start_idx = text.line_to_char(515); let end_idx = text.line_to_char(516); // Remove the line... text.remove(start_idx..end_idx); // ...and replace it with something better. text.insert(start_idx, "The flowers are... so... dunno.\n"); // Print the changes, along with the previous few lines for context. let start_idx = text.line_to_char(511); let end_idx = text.line_to_char(516); println!("{}", text.slice(start_idx..end_idx)); // Write the file back out to disk. text.write_to( BufWriter::new(File::create("my_great_book.txt")?) )?; ``` -------------------------------- ### Rope: Get chunk at byte index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Retrieves information about the chunk containing a specific byte index. Returns an Option tuple containing the string slice, start byte, end byte, and length of the chunk, or None if the index is invalid. ```rust pub fn get_chunk_at_byte( &self, byte_idx: usize, ) -> Option<(&str, usize, usize, usize)> ``` -------------------------------- ### Iterators with State and Indexing Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Lines Methods for iterating with state or index information. ```APIDOC ## Iterator State and Indexing Adapters ### `enumerate(self)` Creates an iterator which gives the current iteration count as well as the next value. - **Method**: `enumerate` ### `scan(initial_state: St, f: F)` An iterator adapter which, like `fold`, holds internal state, but unlike `fold`, produces a new iterator. - **Method**: `scan` - **Parameters**: `initial_state` (St), `f` (FnMut(&mut St, Self::Item) -> Option) ``` -------------------------------- ### Iterator Collection and Partitioning Source: https://docs.rs/ropey/1.6.1/ropey/iter/struct.Lines Methods for collecting iterator items into collections or partitioning them. ```APIDOC ## Iterator Collection and Partitioning Adapters ### `collect(self)` Transforms an iterator into a collection. - **Method**: `collect` - **Returns**: `B` (where `B: FromIterator`) ### `collect_into(self, collection: &mut E)` Collects all the items from an iterator into a collection. - **Method**: `collect_into` - **Parameters**: `collection` (&mut E, where `E: Extend`) - **Returns**: `&mut E` - **Note**: This is a nightly-only experimental API. ### `partition(self, f: F)` Consumes an iterator, creating two collections from it. - **Method**: `partition` - **Parameters**: `f` (FnMut(&Self::Item) -> bool) - **Returns**: `(B, B)` (where `B: Default + Extend`) ### `is_partitioned

(self, predicate: P)` Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return `true` precede all those that return `false`. - **Method**: `is_partitioned` - **Parameters**: `predicate` (FnMut(Self::Item) -> bool) - **Returns**: `bool` - **Note**: This is a nightly-only experimental API. ``` -------------------------------- ### Get Chunk at Character Index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns the chunk of text containing the specified character index, along with the byte and character indices of the chunk's start and its line index. Handles one-past-the-end indices by returning the last chunk. Panics if the character index is out of bounds. Operates in O(log N) time. ```rust pub fn chunk_at_char(&self, char_idx: usize) -> (&str, usize, usize, usize) ``` -------------------------------- ### Mapping Result<&mut T, E> to Result with Clone Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Details the `cloned` method for `Result<&mut T, E>`, which maps the `Ok` variant by cloning its content. This is applicable when `T` implements `Clone`, enabling the creation of new owned values from mutable references. ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Get Chunk at Byte Index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns the chunk of text containing the specified byte index, along with the byte and character indices of the chunk's start and its line index. Handles one-past-the-end indices by returning the last chunk. Panics if the byte index is out of bounds. Operates in O(log N) time. ```rust pub fn chunk_at_byte(&self, byte_idx: usize) -> (&str, usize, usize, usize) ``` -------------------------------- ### Rope: Get line at index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Safely gets a RopeSlice representing a line at the specified index. Returns Some(RopeSlice) if the index is valid, and None otherwise. ```rust pub fn get_line(&self, line_idx: usize) -> Option> ``` -------------------------------- ### Rope Conversion Methods Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Provides non-panicking methods for converting between different indexing schemes (byte, character, line) and encodings (UTF-16 code units). ```APIDOC ## Rope Conversion Methods ### `try_byte_to_line` **Description**: Non-panicking version of `byte_to_line()`. **Method**: GET (conceptual, as these are instance methods) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_char_to_byte` **Description**: Non-panicking version of `char_to_byte()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_char_to_line` **Description**: Non-panicking version of `char_to_line()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_char_to_utf16_cu` **Description**: Non-panicking version of `char_to_utf16_cu()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_utf16_cu_to_char` **Description**: Non-panicking version of `utf16_cu_to_char()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_line_to_byte` **Description**: Non-panicking version of `line_to_byte()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ### `try_line_to_char` **Description**: Non-panicking version of `line_to_char()`. **Method**: GET (conceptual) **Endpoint**: N/A (Instance Method) **Parameters**: #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### Iterate Over Bytes Starting at Index (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.Rope Returns an iterator over the bytes of the Rope, starting from the specified byte index. If the index is one-past-the-end, an empty iterator is returned. Panics if the byte index is out of bounds. Operates in O(log N) time. ```rust pub fn bytes_at(&self, byte_idx: usize) -> Bytes<'_> ``` -------------------------------- ### Creating References from Result with as_ref() Source: https://docs.rs/ropey/1.6.1/ropey/type.Result Demonstrates the `as_ref()` method which converts a `&Result` into a `Result<&T, &E>`. This allows inspecting the contents of a `Result` without taking ownership or modifying it. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Implement PartialOrd for RopeSlice (Rust) Source: https://docs.rs/ropey/1.6.1/ropey/struct.RopeSlice This implementation allows comparing RopeSlice instances with other RopeSlice instances using ordering operators (<, <=, >, >=). The `partial_cmp` method returns an `Option` indicating the comparison result, while `lt`, `le`, `gt`, and `ge` provide boolean results for specific comparisons. ```Rust impl<'a, 'b> PartialOrd> for RopeSlice<'a> { fn partial_cmp(&self, other: &RopeSlice<'b>) -> Option; fn lt(&self, other: &Rhs) -> bool; fn le(&self, other: &Rhs) -> bool; fn gt(&self, other: &Rhs) -> bool; fn ge(&self, other: &Rhs) -> bool; } ```