Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

Commit

Permalink
Remove custom list as it's available already
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrieldemarmiesse committed Apr 1, 2024
1 parent d39deca commit 09155b2
Show file tree
Hide file tree
Showing 15 changed files with 58 additions and 347 deletions.
6 changes: 2 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ repository will soon be obsolete.
```python
from stdlib_extensions.datetime import datetime, timedelta
from stdlib_extensions.builtins.string import rjust
from stdlib_extensions.builtins import list, list_to_str
from stdlib_extensions.builtins import list_to_str

def main():
now = datetime.now()
Expand All @@ -23,7 +23,7 @@ def main():

print(rjust("hello world", 20, "*"))

my_list = list[String]()
my_list = List[String]()
my_list.append("hello")
my_list.append("world")
print(list_to_str(my_list))
Expand Down Expand Up @@ -62,8 +62,6 @@ stdlib_extensions.builtins.string.strip
stdlib_extensions.builtins.hex
stdlib_extensions.builtins.to_bytes
stdlib_extensions.builtins.input
stdlib_extensions.builtins.list
-> append, clear, copy, extend, pop, reverse, insert, __len__, __getitem__, __setitem__
stdlib_extensions.builtins.list_to_str
-> for Int and Strings, because Mojo doesn't support multiple traits for the same type yet
Expand Down
3 changes: 0 additions & 3 deletions run_all_tests.mojo
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from stdlib_extensions.stdlib_tests.builtins import (
test_string,
test_list,
test_bytes,
test_hex,
test_math,
Expand All @@ -23,8 +22,6 @@ from stdlib_extensions.stdlib_tests.uuid import test_uuid_class
def run_each_module():
print("running tests for string")
test_string.run_tests()
print("running tests for list")
test_list.run_tests()
print("running tests for bytes")
test_bytes.run_tests()
print("running tests for hex")
Expand Down
4 changes: 2 additions & 2 deletions stdlib_extensions/builtins/__init__.mojo
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ._generic_list import list, list_to_str
from ._generic_list import list_to_str
from ._bytes import bytes, to_bytes
from ..syscalls.filesystem import read_from_stdin
from ._hash import custom_hash
Expand All @@ -8,7 +8,7 @@ from ._custom_equality import ___eq__


fn input(prompt: String) -> String:
print_no_newline(prompt)
print(prompt, end="")
return input()


Expand Down
5 changes: 2 additions & 3 deletions stdlib_extensions/builtins/_bytes.mojo
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from ._generic_list import list
from .._utils import custom_debug_assert
from .string import rjust


fn get_mapping_byte_to_value() -> list[String]:
var bytes_display = list[String]()
fn get_mapping_byte_to_value() -> List[String]:
var bytes_display = List[String]()
bytes_display.append("\\x00")
bytes_display.append("\\x01")
bytes_display.append("\\x02")
Expand Down
124 changes: 4 additions & 120 deletions stdlib_extensions/builtins/_generic_list.mojo
Original file line number Diff line number Diff line change
@@ -1,123 +1,7 @@
from .._utils import custom_debug_assert


struct ListIter[T: CollectionElement]:
var data: list[T]
var idx: Int

fn __init__(inout self, data: list[T]):
self.idx = -1
self.data = data

fn __len__(self) -> Int:
return len(self.data) - self.idx - 1

fn __next__(inout self) -> T:
self.idx += 1
return self.data[self.idx]


@value
struct list[T: CollectionElement](Sized, Movable):
var _internal_vector: List[T]

fn __init__(inout self):
self._internal_vector = List[T]()

fn __init__(inout self, owned value: List[T]):
self._internal_vector = value

@staticmethod
fn from_values(*values: T) -> list[T]:
var result = list[T]()
for value in values:
result.append(value[])
return result

@always_inline
fn _normalize_index(self, index: Int) -> Int:
if index < 0:
return len(self) + index
else:
return index

fn append(inout self, value: T):
self._internal_vector.append(value)

fn clear(inout self):
self._internal_vector.clear()

fn copy(self) -> list[T]:
return list(self._internal_vector)

fn extend(inout self, other: list[T]):
for i in range(len(other)):
self.append(other[i])

fn pop(inout self, index: Int = -1) -> T:
custom_debug_assert(
index < len(self._internal_vector), "list index out of range"
)
var new_index = self._normalize_index(index)
var element = self[new_index]
for i in range(new_index, len(self) - 1):
self[i] = self[i + 1]
self._internal_vector.resize(len(self._internal_vector) - 1, element)
return element

fn reverse(inout self):
for i in range(len(self) // 2):
var mirror_i = len(self) - 1 - i
var tmp = self[i]
self[i] = self[mirror_i]
self[mirror_i] = tmp

fn insert(inout self, key: Int, value: T):
var index = self._normalize_index(key)
if index >= len(self):
self.append(value)
return
# we increase the size of the array before insertion
self.append(self[-1])
for i in range(len(self) - 2, index, -1):
self[i] = self[i - 1]
self[key] = value

@always_inline
fn __getitem__(self, index: Int) -> T:
custom_debug_assert(
index < len(self._internal_vector), "list index out of range"
)
return self._internal_vector[self._normalize_index(index)]

@always_inline
fn __getitem__(self: Self, limits: Slice) -> Self:
var new_list: Self = Self()
for i in range(limits.start, limits.end, limits.step):
new_list.append(self[i])
return new_list

@always_inline
fn __setitem__(inout self, key: Int, value: T):
custom_debug_assert(key < len(self._internal_vector), "list index out of range")
self._internal_vector[self._normalize_index(key)] = value

@always_inline
fn __len__(self) -> Int:
return len(self._internal_vector)

fn __iter__(self: Self) -> ListIter[T]:
return ListIter(self)

@staticmethod
fn from_string(input_value: String) -> list[String]:
var result = list[String]()
for i in range(len(input_value)):
result.append(input_value[i])
return result


fn list_to_str(input_list: list[String]) -> String:
fn list_to_str(input_list: List[String]) -> String:
var result: String = "["
for i in range(len(input_list)):
var repr = "'" + str(input_list[i]) + "'"
Expand All @@ -128,18 +12,18 @@ fn list_to_str(input_list: list[String]) -> String:
return result + "]"


fn list_to_str(input_list: list[Int]) -> String:
fn list_to_str(input_list: List[Int]) -> String:
var result: String = "["
for i in range(len(input_list)):
var repr = str(input_list.__getitem__(index=i))
var repr = str(input_list[i])
if i != len(input_list) - 1:
result += repr + ", "
else:
result += repr
return result + "]"


fn _cmp_list(a: list[Int], b: list[Int]) -> Int:
fn _cmp_list(a: List[Int], b: List[Int]) -> Int:
for i in range(len(a)):
if i >= len(b):
return 1
Expand Down
3 changes: 1 addition & 2 deletions stdlib_extensions/builtins/_hash.mojo
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
from sys.info import sizeof
from ._generic_list import list


fn custom_hash(x: list[Int]) -> Int:
fn custom_hash(x: List[Int]) -> Int:
"""Very simple hash function."""
var prime = 31
var hash_value = 0
Expand Down
6 changes: 3 additions & 3 deletions stdlib_extensions/builtins/_types.mojo
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
@value
struct Optional[T: CollectionElement](CollectionElement):
var has_value: Bool
var values: list[T]
var values: List[T]

fn __init__(inout self, value: T):
self.has_value = True
self.values = list[T]()
self.values = List[T]()
self.values.append(value)

fn __init__(inout self, value: None):
self.has_value = False
self.values = list[T]()
self.values = List[T]()

fn __is__(self, other: None) -> Bool:
return not self.has_value
Expand Down
18 changes: 12 additions & 6 deletions stdlib_extensions/builtins/string.mojo
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from ..builtins._generic_list import list
from .._utils import custom_debug_assert

alias _ALL_WHITESPACES = " \t\n\r\x0b\f"
Expand Down Expand Up @@ -58,21 +57,28 @@ fn startswith(
return input_string[start : start + len(prefix)] == prefix


fn string_to_list(input_string: String) -> List[String]:
var result = List[String]()
for i in range(len(input_string)):
result.append(input_string[i])
return result


fn split(
input_string: String, sep: String = " ", owned maxsplit: Int = -1
) -> list[String]:
) -> List[String]:
"""The separator can be multiple characters long."""
var result = list[String]()
var result = List[String]()
if maxsplit == 0:
result.append(input_string)
return result
if maxsplit < 0:
maxsplit = len(input_string)

if not sep:
return list[String].from_string(input_string)[0:maxsplit]
return string_to_list(input_string)[0:maxsplit]

var output = list[String]()
var output = List[String]()
var start = 0
var split_count = 0

Expand All @@ -89,7 +95,7 @@ fn split(
return output


fn join(separator: String, iterable: list[String]) -> String:
fn join(separator: String, iterable: List[String]) -> String:
var result: String = ""
for i in range(iterable.__len__()):
result += iterable[i]
Expand Down
7 changes: 3 additions & 4 deletions stdlib_extensions/datetime/_date.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ from ._iso_calendar_date import IsoCalendarDate
from ..builtins._generic_list import _cmp_list
from ..builtins import custom_hash
from ..time import time, time_ns, struct_time
from ..builtins import list
from ..builtins.string import ljust, rjust, join
from .._utils import custom_debug_assert

Expand Down Expand Up @@ -342,12 +341,12 @@ struct date(CollectionElement, Stringable, Hashable):
return self._cmp(other) > 0

fn _cmp(self, other: date) -> Int:
var list_1 = list[Int].from_values(self.year, self.month, self.day)
var list_2 = list[Int].from_values(other.year, other.month, other.day)
var list_1 = List[Int](self.year, self.month, self.day)
var list_2 = List[Int](other.year, other.month, other.day)
return _cmp_list(list_1, list_2)

fn __hash__(self) -> Int:
return custom_hash(list[Int].from_values(self.year, self.month, self.day))
return custom_hash(List[Int](self.year, self.month, self.day))

# Computations
fn __add__(self, other: dt.timedelta) -> date:
Expand Down
8 changes: 4 additions & 4 deletions stdlib_extensions/datetime/_datetime.mojo
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .. import datetime as dt
from ._utils import ymd2ord, MAXORDINAL, _check_date_fields, _check_time_fields
from ..builtins import divmod, list
from ..builtins import divmod
from ..builtins._types import Optional
from .._utils import custom_debug_assert
from ._utils import (
Expand Down Expand Up @@ -413,7 +413,7 @@ struct datetime(CollectionElement, Stringable, Hashable):
fn __repr__(self) -> String:
"""Convert to formal string, for repr()."""
var result: String = "datetime.datetime("
var components = list[String].from_values(
var components = List[String](
str(self.year),
str(self.month),
str(self.day),
Expand All @@ -424,7 +424,7 @@ struct datetime(CollectionElement, Stringable, Hashable):
)
for _ in range(2):
if components[-1] == "0":
components.pop()
components.pop_back()
result += join(", ", components)
if self.tzinfo is not None:
result += ", tzinfo=" + self.tzinfo.value().__repr__()
Expand Down Expand Up @@ -621,7 +621,7 @@ struct datetime(CollectionElement, Stringable, Hashable):
var tzoff = t.utcoffset()
if tzoff is None:
return custom_hash(
list[Int].from_values(
List[Int](
t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond
)
)
Expand Down
Loading

0 comments on commit 09155b2

Please sign in to comment.