bool-hybrid-array 9.6.4__py3-none-any.whl → 9.10.19__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bool_hybrid_array/__init__.py +35 -4
- bool_hybrid_array/__main__.py +284 -0
- bool_hybrid_array/core.py +313 -67
- bool_hybrid_array/int_array/__init__.py +203 -0
- bool_hybrid_array//321/207/320/267/320/250/321/205/320/277/320/226.md +2 -0
- {bool_hybrid_array-9.6.4.dist-info → bool_hybrid_array-9.10.19.dist-info}/METADATA +210 -33
- bool_hybrid_array-9.10.19.dist-info/RECORD +10 -0
- bool_hybrid_array-9.6.4.dist-info/RECORD +0 -7
- {bool_hybrid_array-9.6.4.dist-info → bool_hybrid_array-9.10.19.dist-info}/WHEEL +0 -0
- {bool_hybrid_array-9.6.4.dist-info → bool_hybrid_array-9.10.19.dist-info}/licenses/LICENSE +0 -0
- {bool_hybrid_array-9.6.4.dist-info → bool_hybrid_array-9.10.19.dist-info}/top_level.txt +0 -0
bool_hybrid_array/core.py
CHANGED
|
@@ -2,28 +2,104 @@ from __future__ import annotations
|
|
|
2
2
|
import builtins
|
|
3
3
|
import array,bisect,numpy as np
|
|
4
4
|
from collections.abc import MutableSequence,Iterable,Generator,Iterator,Sequence
|
|
5
|
-
import itertools,copy,sys,math,weakref
|
|
5
|
+
import itertools,copy,sys,math,weakref,random,mmap,os
|
|
6
6
|
from functools import reduce
|
|
7
|
-
import operator,ctypes,gc,abc
|
|
7
|
+
import operator,ctypes,gc,abc,types
|
|
8
|
+
from functools import lru_cache
|
|
9
|
+
from typing import Union,_GenericAlias
|
|
8
10
|
hybrid_array_cache = []
|
|
9
|
-
|
|
10
|
-
class
|
|
11
|
+
if 'UnionType' in types.__dict__:
|
|
12
|
+
class Union:
|
|
13
|
+
def __getitem__(self,*args):
|
|
14
|
+
return reduce(operator.or_, args)
|
|
15
|
+
Union = Union()
|
|
16
|
+
if 'GenericAlias' in types.__dict__:
|
|
17
|
+
_GenericAlias = types.GenericAlias
|
|
18
|
+
class ResurrectMeta(abc.ABCMeta,metaclass=abc.ABCMeta):
|
|
19
|
+
__module__ = 'bool_hybrid_array'
|
|
20
|
+
name = 'ResurrectMeta'
|
|
11
21
|
def __new__(cls, name, bases, namespace):
|
|
12
22
|
meta_bases = tuple(type(base) for base in bases)
|
|
13
23
|
if cls not in meta_bases:
|
|
14
24
|
meta_bases = (cls,) + meta_bases
|
|
15
|
-
|
|
16
|
-
|
|
25
|
+
obj = super().__new__(cls, name, bases, namespace)
|
|
26
|
+
super_cls = super(ResurrectMeta, obj)
|
|
27
|
+
super_cls.__setattr__('x',None)
|
|
28
|
+
super_cls.__setattr__('name', name)
|
|
29
|
+
super_cls.__setattr__('bases', bases)
|
|
30
|
+
super_cls.__setattr__('namespace', namespace)
|
|
31
|
+
super_cls.__setattr__('original_dict', dict(obj.__dict__))
|
|
32
|
+
del obj.original_dict["__abstractmethods__"]
|
|
33
|
+
del obj.original_dict["_abc_impl"]
|
|
34
|
+
return obj
|
|
35
|
+
@lru_cache
|
|
17
36
|
def __str__(cls):
|
|
18
37
|
return super().__repr__()[8:][:-2]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
38
|
+
@lru_cache
|
|
39
|
+
def __repr__(cls,detailed = False):
|
|
40
|
+
if detailed:
|
|
41
|
+
name, bases, namespace = cls.name,cls.bases,cls.namespace
|
|
42
|
+
return f'ResurrectMeta(cls = {cls},{name = },{bases = },{namespace = })'
|
|
43
|
+
return str(cls)
|
|
22
44
|
def __del__(cls):
|
|
23
45
|
exec(f"builtins.{cls.__name__} = cls")
|
|
24
46
|
if not sys.is_finalizing():
|
|
25
|
-
|
|
47
|
+
print(f'警告:禁止删除常变量:{cls}!')
|
|
26
48
|
raise TypeError(f'禁止删除常变量:{cls}')
|
|
49
|
+
def __hash__(cls):
|
|
50
|
+
return hash(cls.name+cls.__module__)
|
|
51
|
+
def __setattr__(cls,name,value):
|
|
52
|
+
if not hasattr(cls, 'x'):
|
|
53
|
+
super().__setattr__(name,value)
|
|
54
|
+
return
|
|
55
|
+
if hasattr(cls, 'name') and cls.name == 'BHA_Bool' and repr(value) in {'T','F'} and name in {'T','F'}:
|
|
56
|
+
super().__setattr__(name,value)
|
|
57
|
+
return
|
|
58
|
+
if hasattr(cls, 'original_dict') and name in cls.original_dict:
|
|
59
|
+
raise AttributeError(f'禁止修改属性:{name}')
|
|
60
|
+
else:
|
|
61
|
+
super().__setattr__(name,value)
|
|
62
|
+
def __delattr__(cls,name):
|
|
63
|
+
if name in cls.original_dict:
|
|
64
|
+
raise AttributeError(f'禁止删除属性:{name}')
|
|
65
|
+
else:
|
|
66
|
+
super().__delattr__(name)
|
|
67
|
+
if 'UnionType' not in types.__dict__:
|
|
68
|
+
def __or__(self,other):
|
|
69
|
+
return Union[self,other]
|
|
70
|
+
__ror__ = __or__
|
|
71
|
+
def __getitem__(self,*args):
|
|
72
|
+
return _GenericAlias(self,args)
|
|
73
|
+
x = None
|
|
74
|
+
original_dict = {"__delattr__":__delattr__,"__getitem__":__getitem__,"__setattr__":__setattr__,"__hash__":__hash__,
|
|
75
|
+
"__new__":__new__,"__del__":__del__,"__str__":__str__,"__repr__":__repr__,"__class__":abc.ABCMeta,"original_dict":None}
|
|
76
|
+
try:
|
|
77
|
+
original_dict["original_dict"] = original_dict
|
|
78
|
+
original_dict["__ror__"] = __ror__
|
|
79
|
+
original_dict["__or__"] = __or__
|
|
80
|
+
except:
|
|
81
|
+
pass
|
|
82
|
+
ResurrectMeta.__class__ = ResurrectMeta
|
|
83
|
+
class BHA_Function(metaclass=ResurrectMeta):
|
|
84
|
+
def __init__(self,v):
|
|
85
|
+
self.data,self.module = v,__name__
|
|
86
|
+
def __call__(self,*a,**b):
|
|
87
|
+
return self.data(*a,**b)
|
|
88
|
+
def __getattr__(self,name):
|
|
89
|
+
return getattr(self.data,name)
|
|
90
|
+
@classmethod
|
|
91
|
+
def string_define(cls, name, text, positional, default):
|
|
92
|
+
param_strs = list(positional)
|
|
93
|
+
param_strs.extend([f"{k}={v!r}" for k, v in default.items()])
|
|
94
|
+
params = ", ".join(param_strs)
|
|
95
|
+
func_code = f"""
|
|
96
|
+
def {name}({params}):
|
|
97
|
+
{text}
|
|
98
|
+
"""
|
|
99
|
+
local_namespace = {}
|
|
100
|
+
exec(func_code, globals(), local_namespace)
|
|
101
|
+
dynamic_func = local_namespace[name]
|
|
102
|
+
return cls(dynamic_func)
|
|
27
103
|
class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
28
104
|
__module__ = 'bool_hybrid_array'
|
|
29
105
|
class _CompactBoolArray(Sequence,Exception):
|
|
@@ -45,10 +121,13 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
45
121
|
val_bool = bool(value)
|
|
46
122
|
for i in indices:
|
|
47
123
|
self._set_single(i, val_bool, ctypes_arr)
|
|
124
|
+
self.data = np.ctypeslib.as_array(ctypes_arr, shape=(self.n_uint8,))
|
|
48
125
|
return
|
|
49
126
|
if not (0 <= index < self.size):
|
|
50
127
|
raise IndexError(f"密集区索引 {index} 超出范围 [0, {self.size})")
|
|
51
128
|
self._set_single(index, bool(value), ctypes_arr)
|
|
129
|
+
self.data = np.ctypeslib.as_array(ctypes_arr, shape=(self.n_uint8,))
|
|
130
|
+
self.data = self.data.view()
|
|
52
131
|
def _set_single(self, index: int, value: bool, ctypes_arr):
|
|
53
132
|
uint8_pos = index >> 3
|
|
54
133
|
bit_offset = index & 7
|
|
@@ -76,6 +155,10 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
76
155
|
length = len(self.data)
|
|
77
156
|
if value:ctypes.memset(ctypes_arr, 0xff, length)
|
|
78
157
|
else:ctypes.memset(ctypes_arr, 0, length)
|
|
158
|
+
def copy(self):
|
|
159
|
+
new_instance = self.__class__(size=self.size)
|
|
160
|
+
new_instance.data = self.data.copy()
|
|
161
|
+
return new_instance
|
|
79
162
|
def __init__(self, split_index: int, size=None, is_sparse=False ,Type:Callable = None,hash_ = True) -> None:
|
|
80
163
|
self.Type = Type if Type is not None else builtins.BHA_Bool
|
|
81
164
|
self.split_index = int(split_index)
|
|
@@ -189,7 +272,7 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
189
272
|
raise IndexError(f"小索引 {key} 超出small数组范围(长度{len(self.small)})")
|
|
190
273
|
self.small = np.delete(self.small, key)
|
|
191
274
|
self.small = np.append(self.small, not self.is_sparse)
|
|
192
|
-
self.split_index
|
|
275
|
+
self.split_index -= min(self.split_index, len(self.small) - 1)
|
|
193
276
|
else:
|
|
194
277
|
pos = bisect.bisect_left(self.large, key)
|
|
195
278
|
if pos < len(self.large) and self.large[pos] == key:
|
|
@@ -223,22 +306,26 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
223
306
|
def __len__(self) -> int:
|
|
224
307
|
return self.size
|
|
225
308
|
def __iter__(self):
|
|
226
|
-
return BHA_Iterator(self
|
|
309
|
+
return BHA_Iterator(map(self.__getitem__,range(self.size)))
|
|
227
310
|
def __next__(self):
|
|
228
311
|
return next(self.generator)
|
|
229
312
|
def __contains__(self, value) -> bool:
|
|
230
313
|
if not isinstance(value, (bool,np.bool_,self.Type,BHA_bool)):return False
|
|
231
|
-
|
|
314
|
+
if not self.size:return False
|
|
315
|
+
for i in range(10):
|
|
316
|
+
if self[random.randint(0,self.size-1)] == value:
|
|
317
|
+
return True
|
|
318
|
+
b = any(1 for i in range(self.small.size+1>>1) if value==self.small[i] or value==self.small[self.small.size-i-1])
|
|
232
319
|
if value == self.is_sparse:
|
|
233
320
|
return self.large or b
|
|
234
321
|
else:
|
|
235
322
|
return len(self.large) == self.size-self.split_index-1 or b
|
|
236
323
|
def __bool__(self) -> bool:
|
|
237
|
-
return self.size
|
|
324
|
+
return self.size
|
|
238
325
|
def __any__(self):
|
|
239
|
-
return self
|
|
326
|
+
return T in self
|
|
240
327
|
def __all__(self):
|
|
241
|
-
return self
|
|
328
|
+
return F not in self
|
|
242
329
|
def __eq__(self, other) -> bool:
|
|
243
330
|
if not isinstance(other, (BoolHybridArray, list, tuple, np.ndarray, array.array)):
|
|
244
331
|
return False
|
|
@@ -255,9 +342,9 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
255
342
|
raise ValueError(f"与运算要求数组长度相同({len(self)} vs {len(other)})")
|
|
256
343
|
return BoolHybridArr(map(operator.and_, self, other),hash_ = self.hash_)
|
|
257
344
|
def __int__(self):
|
|
258
|
-
if self.size
|
|
345
|
+
if not self.size:
|
|
259
346
|
return 0
|
|
260
|
-
return reduce(lambda acc, val: operator.or_(operator.lshift(acc, 1), val),self,0)
|
|
347
|
+
return reduce(lambda acc, val: operator.or_(operator.lshift(acc, 1), int(val)),self,0)
|
|
261
348
|
def __or__(self, other) -> BoolHybridArray:
|
|
262
349
|
if type(other) == int:
|
|
263
350
|
other = bin(other)[2:]
|
|
@@ -316,14 +403,15 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
316
403
|
def __invert__(self) -> BoolHybridArray:
|
|
317
404
|
return BoolHybridArr(not a for a in self)
|
|
318
405
|
def copy(self) -> BoolHybridArray:
|
|
319
|
-
arr =
|
|
320
|
-
arr.large,arr.small,arr.split_index,arr.is_sparse,arr.Type = (self.large,self.small,
|
|
321
|
-
self.split_index,self.is_sparse,self.Type)
|
|
406
|
+
arr = BoolHybridArray(split_index = self.split_index,size = self.size)
|
|
407
|
+
arr.large,arr.small,arr.split_index,arr.is_sparse,arr.Type,arr.size = (array.array(self.large.typecode, self.large),self.small.copy(),
|
|
408
|
+
self.split_index,BHA_Bool(self.is_sparse),self.Type,self.size)
|
|
322
409
|
return arr
|
|
323
410
|
def __copy__(self) -> BoolHybridArray:
|
|
324
411
|
return self.copy()
|
|
325
412
|
def find(self,value):
|
|
326
|
-
|
|
413
|
+
from .int_array import IntHybridArray
|
|
414
|
+
return IntHybridArray([i for i in range(len(self)) if self[i]==value])
|
|
327
415
|
def extend(self, iterable:Iterable) -> None:
|
|
328
416
|
if isinstance(iterable, (Iterator, Generator, map)):
|
|
329
417
|
iterable,copy = itertools.tee(iterable, 2)
|
|
@@ -337,13 +425,30 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
337
425
|
self.size += 1
|
|
338
426
|
self[-1] = v
|
|
339
427
|
def index(self, value) -> int:
|
|
428
|
+
if self.size == 0:
|
|
429
|
+
raise ValueError('无法在空的 BoolHybridArray 中查找元素!')
|
|
340
430
|
value = bool(value)
|
|
341
431
|
x = 'not find'
|
|
342
432
|
for i in range(self.size):
|
|
343
433
|
if self[i] == value:
|
|
344
434
|
return i
|
|
345
|
-
|
|
346
|
-
x =
|
|
435
|
+
if self[-i] == value:
|
|
436
|
+
x = self.size-i
|
|
437
|
+
if len(self)-i == i:
|
|
438
|
+
break
|
|
439
|
+
if x != 'not find':
|
|
440
|
+
return x
|
|
441
|
+
raise ValueError(f"{value} not in BoolHybridArray")
|
|
442
|
+
def rindex(self, value) -> int:
|
|
443
|
+
if self.size == 0:
|
|
444
|
+
raise ValueError('无法在空的 BoolHybridArray 中查找元素!')
|
|
445
|
+
value = bool(value)
|
|
446
|
+
x = 'not find'
|
|
447
|
+
for i in range(self.size):
|
|
448
|
+
if self[-i] == value:
|
|
449
|
+
return -i
|
|
450
|
+
if self[i] == value:
|
|
451
|
+
x = -(self.size-i)
|
|
347
452
|
if len(self)-i == i:
|
|
348
453
|
break
|
|
349
454
|
if x != 'not find':
|
|
@@ -389,6 +494,15 @@ class BoolHybridArray(MutableSequence,Exception,metaclass=ResurrectMeta):
|
|
|
389
494
|
}
|
|
390
495
|
def get_shape(self):
|
|
391
496
|
return (self.size,)
|
|
497
|
+
def __array__(self,dtype = np.bool_,copy = None):
|
|
498
|
+
arr = np.fromiter(map(np.bool_,self), dtype=dtype)
|
|
499
|
+
return arr.copy() if copy else arr.view()
|
|
500
|
+
def view(self):
|
|
501
|
+
arr = TruesArray(0)
|
|
502
|
+
arr.__dict__ = self.__dict__
|
|
503
|
+
return arr
|
|
504
|
+
def __reduce__(self):
|
|
505
|
+
return BoolHybridArr,(np.asarray(self),self.is_sparse,self.Type,self.hash_,),
|
|
392
506
|
class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
393
507
|
__module__ = 'bool_hybrid_array'
|
|
394
508
|
def __new__(cls, lst: Iterable, is_sparse=None, Type = None, hash_ = True) -> BoolHybridArray:
|
|
@@ -407,7 +521,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
407
521
|
split_index = int(min(size * 0.8, math.sqrt(size) * 100))
|
|
408
522
|
split_index = math.isqrt(size) if true_count>size/3*2 or true_count<size/3 else max(split_index, 1)
|
|
409
523
|
split_index = int(split_index) if split_index < 150e+7*2 else int(145e+7*2)
|
|
410
|
-
arr = BoolHybridArray(split_index, size, is_sparse, Type, hash_ = F)
|
|
524
|
+
arr = BoolHybridArray(split_index = split_index, size = size, is_sparse = is_sparse, Type = Type, hash_ = F)
|
|
411
525
|
small_max_idx = min(split_index, size - 1)
|
|
412
526
|
if a:
|
|
413
527
|
small_data = []
|
|
@@ -436,6 +550,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
436
550
|
arr.large = array.array(type_, arr.large)
|
|
437
551
|
if hash_:
|
|
438
552
|
global hybrid_array_cache
|
|
553
|
+
del hybrid_array_cache[-1]
|
|
439
554
|
hybrid_array_cache = [
|
|
440
555
|
(ref, h) for ref, h in hybrid_array_cache
|
|
441
556
|
if ref() is not None
|
|
@@ -448,7 +563,7 @@ class BoolHybridArr(BoolHybridArray,metaclass=ResurrectMeta):
|
|
|
448
563
|
elif arr == existing_array:
|
|
449
564
|
arr._cached_hash = existing_hash
|
|
450
565
|
return arr
|
|
451
|
-
except
|
|
566
|
+
except:
|
|
452
567
|
continue
|
|
453
568
|
return arr
|
|
454
569
|
def TruesArray(size, Type = None, hash_ = True):
|
|
@@ -470,36 +585,39 @@ class BHA_bool(int,metaclass=ResurrectMeta):
|
|
|
470
585
|
instance.data = Bool_Array[1] if core_value else Bool_Array[0]
|
|
471
586
|
instance.value = core_value
|
|
472
587
|
return instance
|
|
588
|
+
@lru_cache
|
|
473
589
|
def __str__(self):
|
|
474
590
|
return 'True' if self else 'False'
|
|
591
|
+
@lru_cache
|
|
475
592
|
def __repr__(self):
|
|
476
593
|
return 'T' if self else 'F'
|
|
594
|
+
@lru_cache
|
|
477
595
|
def __bool__(self):
|
|
478
596
|
return self.value
|
|
597
|
+
@lru_cache
|
|
479
598
|
def __int__(self):
|
|
480
599
|
return int(self.data)
|
|
481
|
-
|
|
482
|
-
return self.value is bool(other)
|
|
600
|
+
@lru_cache
|
|
483
601
|
def __or__(self,other):
|
|
484
602
|
return BHA_Bool(self.value|other)
|
|
603
|
+
@lru_cache
|
|
485
604
|
def __and__(self,other):
|
|
486
605
|
return BHA_Bool(self.value&other)
|
|
606
|
+
@lru_cache
|
|
487
607
|
def __xor__(self,other):
|
|
488
608
|
return BHA_Bool(self.value^other)
|
|
489
|
-
def
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
else:builtins.F = self
|
|
494
|
-
if not sys.is_finalizing():
|
|
495
|
-
raise TypeError(f'禁止删除常变量{repr(self)}!')
|
|
609
|
+
def __hash__(self):
|
|
610
|
+
return hash(self.data)
|
|
611
|
+
def __len__(self):
|
|
612
|
+
raise TypeError("'BHA_bool' object has no attribute '__len__'")
|
|
496
613
|
__rand__,__ror__,__rxor__ = __and__,__or__,__xor__
|
|
497
614
|
class BHA_Bool(BHA_bool,metaclass=ResurrectMeta):
|
|
498
615
|
__module__ = 'bool_hybrid_array'
|
|
616
|
+
@lru_cache
|
|
499
617
|
def __new__(cls,v):
|
|
500
|
-
|
|
501
|
-
return T if v else F
|
|
502
|
-
|
|
618
|
+
if(builtins.T == True)and(builtins.F == False):
|
|
619
|
+
return builtins.T if v else builtins.F
|
|
620
|
+
else:
|
|
503
621
|
builtins.T,builtins.F = BHA_Bool.T,BHA_Bool.F
|
|
504
622
|
return BHA_Bool.T if v else BHA_Bool.F
|
|
505
623
|
class BHA_List(list,metaclass=ResurrectMeta):
|
|
@@ -517,12 +635,16 @@ class BHA_List(list,metaclass=ResurrectMeta):
|
|
|
517
635
|
else:
|
|
518
636
|
return v
|
|
519
637
|
super().__init__(map(Temp,arr))
|
|
638
|
+
try:self.hash_value = sum(map(hash,self))
|
|
639
|
+
except Exception as e:return hash(e)
|
|
640
|
+
def __hash__(self):
|
|
641
|
+
return self.hash_value
|
|
520
642
|
def __call__(self, func):
|
|
521
643
|
func.self = self
|
|
522
|
-
def wrapper(
|
|
644
|
+
def wrapper(*args, **kwargs):
|
|
523
645
|
return func(self, *args, **kwargs)
|
|
524
646
|
setattr(self, func.__name__, wrapper)
|
|
525
|
-
return
|
|
647
|
+
return func
|
|
526
648
|
def __str__(self):
|
|
527
649
|
def Temp(v):
|
|
528
650
|
if isinstance(v,(BoolHybridArray,np.ndarray,BHA_List,array.array)):
|
|
@@ -576,32 +698,137 @@ class BHA_Iterator(Iterator,metaclass=ResurrectMeta):
|
|
|
576
698
|
return BHA_Iterator(map(operator.and_, self, other))
|
|
577
699
|
def __xor__(self,other):
|
|
578
700
|
return BHA_Iterator(map(operator.xor, self, other))
|
|
701
|
+
def __array__(self,dtype = None,copy = None):
|
|
702
|
+
arr = np.fromiter(self, dtype=dtype)
|
|
703
|
+
return arr.copy() if copy else arr.view()
|
|
579
704
|
__rand__,__ror__,__rxor__ = __and__,__or__,__xor__
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
705
|
+
class ProtectedBuiltinsDict(dict,metaclass=ResurrectMeta):
|
|
706
|
+
def __init__(self, *args, protected_names = ["T", "F", "BHA_Bool", "BHA_List", "BoolHybridArray", "BoolHybridArr",
|
|
707
|
+
"TruesArray", "FalsesArray", "ProtectedBuiltinsDict", "builtins",
|
|
708
|
+
"__builtins__", "__dict__","ResurrectMeta","math",
|
|
709
|
+
"np","protected_names","BHA_Function",
|
|
710
|
+
"__class__","Ask_BHA","Create_BHA","Ask_arr","numba_opt"],
|
|
711
|
+
name = 'builtins', **kwargs):
|
|
712
|
+
super().__init__(*args, **kwargs)
|
|
713
|
+
if name == 'builtins':
|
|
714
|
+
super().__setattr__('__dict__',self)
|
|
715
|
+
super().__setattr__('builtins',self)
|
|
716
|
+
super().__setattr__('__builtins__',self)
|
|
717
|
+
self.name = name
|
|
718
|
+
self.protected_names = protected_names
|
|
719
|
+
def __setitem__(self, name, value):
|
|
720
|
+
if name in ["T", "F"]:
|
|
721
|
+
current_T = self.get("T")
|
|
722
|
+
current_F = self.get("F")
|
|
723
|
+
if isinstance(current_T, BHA_bool) and isinstance(current_F, BHA_bool):
|
|
724
|
+
is_swap = (name == "T" and isinstance(value, BHA_bool) and value.value == current_F.value)or(name == "F" and isinstance(value, BHA_bool) and value.value == current_T.value)
|
|
725
|
+
if is_swap:
|
|
726
|
+
print(f"""警告:禁止交换内置常量 __{self.name}__["{name}"] 和 __builtins__["{'F' if name == 'T' else 'T'}"]!""")
|
|
727
|
+
raise AttributeError(f"""禁止交换内置常量 __{self.name}__["{name}"] 和 __{self.name}__["{'F' if name == 'T' else 'T'}"]""")
|
|
728
|
+
if name in self.protected_names and name not in ["T", "F"]:
|
|
729
|
+
print(f"警告:禁止修改内置常量 __{self.name}__['{name}']!")
|
|
730
|
+
raise AttributeError(f"禁止修改内置常量 __{self.name}__['{name}']")
|
|
731
|
+
super().__setitem__(name, value)
|
|
732
|
+
def __delitem__(self, name):
|
|
733
|
+
if name in self.protected_names:
|
|
734
|
+
print(f"警告:禁止删除内置常量 __builtins__['{name}']!")
|
|
735
|
+
raise AttributeError(f"禁止删除内置常量 __builtins__['{name}']")
|
|
736
|
+
if name in self:
|
|
737
|
+
super().__delitem__(name)
|
|
738
|
+
def __delattr__(self, name):
|
|
739
|
+
if name in self.protected_names:
|
|
740
|
+
raise AttributeError(f'禁止删除内置常量:{self.name}.{name}')
|
|
741
|
+
else:
|
|
742
|
+
del self[name]
|
|
743
|
+
def __getattr__(self, name):
|
|
744
|
+
if name in self:
|
|
745
|
+
return self[name]
|
|
746
|
+
else:
|
|
747
|
+
raise AttributeError(f"module 'builtins' has no attribute '{name}'")
|
|
748
|
+
def __setattr__(self,name,value):
|
|
749
|
+
try:protected = self.protected_names
|
|
750
|
+
except Exception:protected = self
|
|
751
|
+
if(name in protected)and(not sys.is_finalizing())and(name != '_'):
|
|
752
|
+
raise AttributeError(f'禁止修改内置常量:{self.name}.{name}')
|
|
753
|
+
else:
|
|
754
|
+
super().__setattr__(name,value)
|
|
755
|
+
def __import__(self, name, globals=None, locals=None, fromlist=(), level=0):
|
|
756
|
+
if fromlist:
|
|
757
|
+
result = []
|
|
758
|
+
for key in fromlist:
|
|
759
|
+
if key not in self:
|
|
760
|
+
raise AttributeError(f"'ImportableDict' object has no attribute '{key}'")
|
|
761
|
+
result.append(self[key])
|
|
762
|
+
return result[0] if len(result) == 1 else tuple(result)
|
|
763
|
+
return self
|
|
764
|
+
def Ask_arr(arr):
|
|
765
|
+
if isinstance(arr,BHA_List):
|
|
766
|
+
return '\n'.join(map(Ask_arr,arr))
|
|
767
|
+
elif isinstance(arr,BoolHybridArray):
|
|
768
|
+
h = hex(int(arr))[2:]
|
|
769
|
+
h = '0'*(arr.size - len(bin(int(arr)))+2)+h
|
|
770
|
+
return h
|
|
771
|
+
else:
|
|
772
|
+
return str(arr)
|
|
773
|
+
def Ask_BHA(path):
|
|
774
|
+
if '.bha' not in path.lower():
|
|
775
|
+
path += '.bha'
|
|
776
|
+
with open(path, 'a+b') as f:
|
|
777
|
+
f.seek(0)
|
|
778
|
+
file_size = os.fstat(f.fileno()).st_size
|
|
779
|
+
if not file_size:
|
|
780
|
+
return TruesArray(0)
|
|
781
|
+
if os.name == 'nt':
|
|
782
|
+
mm = mmap.mmap(f.fileno(), file_size, access=mmap.ACCESS_READ)
|
|
783
|
+
else:
|
|
784
|
+
mm = mmap.mmap(f.fileno(), file_size, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ)
|
|
785
|
+
with mm:
|
|
786
|
+
temp = mm.read().decode('utf-8').strip()
|
|
787
|
+
temp = temp.split()
|
|
788
|
+
temp2 = lambda x:BoolHybridArr(map(int,'0'*(len(x) - len(x.lstrip('0')))+bin(int(x,base = 16))[2:]),hash_ = F)
|
|
789
|
+
temp = BHA_List(map(temp2,temp))
|
|
790
|
+
if len(temp) == 1:
|
|
791
|
+
return temp[0]
|
|
792
|
+
return temp
|
|
793
|
+
def Create_BHA(path,arr):
|
|
794
|
+
if '.bha' not in path.lower():
|
|
795
|
+
path += '.bha'
|
|
796
|
+
temp = Ask_arr(arr).strip().encode('utf-8')
|
|
797
|
+
with open(path, "w+b") as f:
|
|
798
|
+
f.truncate(len(temp))
|
|
799
|
+
if not len(temp):
|
|
800
|
+
return
|
|
801
|
+
with mmap.mmap(
|
|
802
|
+
f.fileno(),
|
|
803
|
+
length=len(temp),
|
|
804
|
+
access=mmap.ACCESS_WRITE
|
|
805
|
+
) as mm:
|
|
806
|
+
mm[:] = temp
|
|
807
|
+
mm.flush()
|
|
808
|
+
def numba_opt():
|
|
809
|
+
import numba
|
|
810
|
+
sig = numba.types.Union([
|
|
811
|
+
numba.types.intp(
|
|
812
|
+
numba.types.Array(numba.types.uint32, 1, 'C'),
|
|
813
|
+
numba.types.uint32,
|
|
814
|
+
numba.types.uint32,
|
|
815
|
+
numba.types.Optional(numba.types.uint32)
|
|
816
|
+
),
|
|
817
|
+
numba.types.intp(
|
|
818
|
+
numba.types.Array(numba.types.uint64, 1, 'C'),
|
|
819
|
+
numba.types.uint64,
|
|
820
|
+
numba.types.uint64,
|
|
821
|
+
numba.types.Optional(numba.types.uint64)
|
|
822
|
+
),
|
|
823
|
+
numba.types.intp(
|
|
824
|
+
numba.types.Any,
|
|
825
|
+
numba.types.Any,
|
|
826
|
+
numba.types.Any,
|
|
827
|
+
numba.types.Optional(numba.types.Any)
|
|
828
|
+
)
|
|
829
|
+
])
|
|
830
|
+
bisect.bisect_left = numba.njit(sig, cache=True)(bisect.bisect_left)
|
|
831
|
+
bisect.bisect_right = numba.njit(sig, cache=True)(bisect.bisect_right)
|
|
605
832
|
builtins.np = np
|
|
606
833
|
builtins.T = BHA_bool(1)
|
|
607
834
|
builtins.F = BHA_bool(0)
|
|
@@ -612,6 +839,25 @@ builtins.TruesArray = TruesArray
|
|
|
612
839
|
builtins.BoolHybridArr = BoolHybridArr
|
|
613
840
|
builtins.BHA_Iterator = BHA_Iterator
|
|
614
841
|
builtins.BoolHybridArray = BoolHybridArray
|
|
615
|
-
builtins.builtins = builtins
|
|
616
842
|
builtins.BHA_Bool.T,builtins.BHA_Bool.F = BHA_bool(1),BHA_bool(0)
|
|
617
|
-
builtins.ResurrectMeta = ResurrectMeta
|
|
843
|
+
builtins.ResurrectMeta = ResurrectMeta
|
|
844
|
+
builtins.ProtectedBuiltinsDict = ProtectedBuiltinsDict
|
|
845
|
+
builtins.BHA_Function = BHA_Function
|
|
846
|
+
builtins.Ask_BHA = Ask_BHA
|
|
847
|
+
builtins.Create_BHA = Create_BHA
|
|
848
|
+
builtins.numba_opt = numba_opt
|
|
849
|
+
Tid,Fid = id(T),id(F)
|
|
850
|
+
original_id = builtins.id
|
|
851
|
+
def fake_id(obj):
|
|
852
|
+
if isinstance(obj, BHA_bool):return Tid if obj else Fid
|
|
853
|
+
else:return original_id(obj)
|
|
854
|
+
builtins.id = fake_id
|
|
855
|
+
original_builtins_dict = builtins.__dict__.copy()
|
|
856
|
+
__builtins__ = ProtectedBuiltinsDict(original_builtins_dict)
|
|
857
|
+
builtins = __builtins__
|
|
858
|
+
sys.modules['builtins'] = builtins
|
|
859
|
+
builtins.name = 'builtins'
|
|
860
|
+
try:
|
|
861
|
+
sys.flags.optimize = 2
|
|
862
|
+
except:
|
|
863
|
+
pass
|