extension String {
    /// Returns the range of the prefix of the specified length.
    /// If the specified length exceeds the length of the string, returns `nil`.
    ///
    /// - Parameter length: The number of characters in the prefix.
    /// - Returns: A range corresponding to the prefix, or `nil` if the length is invalid.
    func rangeOfPrefix(length: Int) -> Range<String.Index>? {
        guard length >= 0, length <= self.count else { return nil }
        let endIndex = self.index(self.startIndex, offsetBy: length)
        return self.startIndex ..< endIndex
    }

    /// Returns the range of the suffix of the specified length.
    /// If the specified length exceeds the length of the string, returns `nil`.
    ///
    /// - Parameter length: The number of characters in the suffix.
    /// - Returns: A range corresponding to the suffix, or `nil` if the length is invalid.
    func rangeOfSuffix(length: Int) -> Range<String.Index>? {
        guard length >= 0, length <= self.count else { return nil }
        let startIndex = self.index(self.endIndex, offsetBy: -length)
        return startIndex ..< self.endIndex
    }

    /// Returns a custom range from a start and end index, clamped to the string's bounds.
    ///
    /// - Parameters:
    ///   - start: The start index offset from the beginning of the string.
    ///   - end: The end index offset from the beginning of the string.
    /// - Returns: A clamped range between the start and end indices.
    func clampedRange(start: Int, end: Int) -> Range<String.Index> {
        let safeStart = max(0, min(start, self.count))
        let safeEnd = max(safeStart, min(end, self.count))
        let startIndex = self.index(self.startIndex, offsetBy: safeStart)
        let endIndex = self.index(self.startIndex, offsetBy: safeEnd)
        return startIndex ..< endIndex
    }

    func safeUtf16Distance(from: String.Index, to: String.Index) -> Int? {
        guard from <= to, from >= self.startIndex, to <= self.endIndex else {
            return nil // This ensures that both indices are within the string's bounds.
        }
        return self.utf16.distance(from: from, to: to)
    }
}
