-
-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
typed_array.rb
73 lines (59 loc) 路 1.38 KB
/
typed_array.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# frozen_string_literal: true
# typed: true
module T::Types
class TypedArray < TypedEnumerable
# overrides Base
def name
"T::Array[#{type.name}]"
end
def underlying_class
Array
end
# overrides Base
def recursively_valid?(obj)
obj.is_a?(Array) && super
end
# overrides Base
def valid?(obj)
obj.is_a?(Array)
end
def new(*args)
Array.new(*T.unsafe(args))
end
module Private
module Pool
CACHE_FROZEN_OBJECTS = begin
ObjectSpace::WeakMap.new[1] = 1
true # Ruby 2.7 and newer
rescue ArgumentError # Ruby 2.6 and older
false
end
@cache = ObjectSpace::WeakMap.new
def self.type_for_module(mod)
cached = @cache[mod]
return cached if cached
type = TypedArray.new(mod)
if CACHE_FROZEN_OBJECTS || (!mod.frozen? && !type.frozen?)
@cache[mod] = type
end
type
end
end
end
class Untyped < TypedArray
def initialize
super(T.untyped)
end
def valid?(obj)
obj.is_a?(Array)
end
def freeze
build_type # force lazy initialization before freezing the object
super
end
module Private
INSTANCE = Untyped.new.freeze
end
end
end
end