mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[stdlib] [Feature Request] Refactor `String` to not have so many raises and use Optional

Open martinvuyk opened this issue 9 months ago • 6 comments

Review Mojo's priorities

What is your request?

As title.

What is your motivation for this change?

Could have a fn () raising -> Int and an fn () -> Optional[Int]

fn atol(str: String, base: Int = 10) raises -> Int:
    return _atol(str._strref_dangerous(), base)

fn atol_safe(str: String, base: Int = 10) -> Optional[Int]:
    try:
      return _atol(str._strref_dangerous(), base)(str, base)
    except:
      return None

This could just return a list with one item, it being the whole String. if not delimiter: return List[String](self)

    fn split(self, delimiter: String) raises -> List[String]:
        """Split the string by a delimiter.

        Args:
          delimiter: The string to split on.

        Returns:
          A List of Strings containing the input split by the delimiter.

        Raises:
          Error if an empty delimiter is specified.
        """
        if not delimiter:
            raise Error("empty delimiter not allowed to be passed to split.")

This will most certainly always be checked against anyway with if index == -1: ... so it could also be made an Optional[Int]

fn find(self, substr: String, start: Int = 0) -> Int:
        """Finds the offset of the first occurrence of `substr` starting at
        `start`. If not found, returns -1.

        Args:
          substr: The substring to find.
          start: The offset from which to find.

        Returns:
          The offset of `substr` relative to the beginning of the string.
        """

        return self._strref_dangerous().find(
            substr._strref_dangerous(), start=start
        )

Any other details?

No response

martinvuyk avatar May 16 '24 19:05 martinvuyk