• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#
4# Copyright (c) 2024 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17
18from collections.abc import Iterator
19from typing import Any, Generic, Iterable, List, Optional, TypeVar
20
21from rich.repr import rich_repr
22
23from .base import arkts_str_list
24from .primitive import PrimitiveMeta
25
26T = TypeVar("T")
27
28
29@rich_repr
30class Array(Generic[T], metaclass=PrimitiveMeta):
31    """Base class for ArkTS mirror primitives."""
32
33    __slots__ = ("_cls_name", "_items")
34
35    def __init__(self, cls_name: str, items: List[T] | None = None) -> None:
36        self._cls_name = cls_name
37        self._items = [*items] if items is not None else []
38
39    def __eq__(self, other: Any) -> bool:
40        if self is other:
41            return True
42        if not isinstance(other, Array):
43            return False
44        if self._cls_name != other._cls_name:
45            return False
46        return self._items == other._items
47
48    # CC-OFFNXT(G.NAM.05) Standard function from rich package
49    def __rich_repr__(self):
50        yield self._cls_name
51        yield self._items
52
53    # CC-OFFNXT(G.NAM.05) internal function name
54    def __arkts_str__(self, *, depth: Optional[int] = None) -> str:
55        if depth == 0:
56            return "[...]"
57        next_depth = depth - 1 if depth is not None else None
58        childs = ", ".join(arkts_str_list(self._items, depth=next_depth))
59        return f"[{childs}]"
60
61    def __iter__(self) -> Iterator[T]:
62        return self._items.__iter__()
63
64    def __getitem__(self, *args, **kwargs) -> T:
65        return self._items.__getitem__(*args, **kwargs)
66
67
68def mirror_array(cls_name: str, items: Iterable[Any]) -> Array:
69    return Array(cls_name=cls_name, items=list(items))
70