Skip to content

Commit c287366

Browse files
nevanssaturnflyer
andcommitted
✨ Add Data polyfill for ruby 3.1
For new data structs, I don't want to commit to supporting the entire Struct API and I'd prefer frozen by default. `Data` is exactly what I want but it's not available until ruby 3.2. So this adds a DataLite class that closely matches ruby 3.2's Data class and can be a drop-in replacement for Data. Net::IMAP::Data is an alias for Net::IMAP::DataLite, so when we remove this implementation, the constant will resolve to ruby's ::Data. The most noticable incompatibility is that member names must be valid local variable names. Ideally, we wouldn't define this on newer ruby versions at all, but that breaks the YAML serialization for our test fixtures. So, on newer versions of ruby, this class inherits from `Data` and only reimplements the two methods that are needed for YAML serialization. This serves the additional purpose of ensuring that the same tests pass for both the core `Data` class and our reimplementation. Most of the test code and some of the implementation code has been copied from the polyfill-data gem and updated so that they use "Data" as it is resolved inside the "Net::IMAP" namespace. Copyright notices have been added to the appropriate files to satisfy the MIT license terms. Co-authored-by: Jim Gay <jim@saturnflyer.com>
1 parent f6cf182 commit c287366

File tree

3 files changed

+571
-0
lines changed

3 files changed

+571
-0
lines changed

lib/net/imap.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3295,6 +3295,7 @@ def self.saslprep(string, **opts)
32953295
require_relative "imap/config"
32963296
require_relative "imap/command_data"
32973297
require_relative "imap/data_encoding"
3298+
require_relative "imap/data_lite"
32983299
require_relative "imap/flags"
32993300
require_relative "imap/response_data"
33003301
require_relative "imap/response_parser"

lib/net/imap/data_lite.rb

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
# frozen_string_literal: true
2+
3+
# Some of the code in this file was copied from the polyfill-data gem.
4+
#
5+
# MIT License
6+
#
7+
# Copyright (c) 2023 Jim Gay, Joel Drapper, Nicholas Evans
8+
#
9+
# Permission is hereby granted, free of charge, to any person obtaining a copy
10+
# of this software and associated documentation files (the "Software"), to deal
11+
# in the Software without restriction, including without limitation the rights
12+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13+
# copies of the Software, and to permit persons to whom the Software is
14+
# furnished to do so, subject to the following conditions:
15+
#
16+
# The above copyright notice and this permission notice shall be included in all
17+
# copies or substantial portions of the Software.
18+
#
19+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25+
# SOFTWARE.
26+
27+
28+
module Net
29+
class IMAP
30+
data_or_object = RUBY_VERSION >= "3.2.0" ? ::Data : Object
31+
class DataLite < data_or_object
32+
def encode_with(coder) coder.map = attributes.transform_keys(&:to_s) end
33+
def init_with(coder) initialize(**coder.map.transform_keys(&:to_sym)) end
34+
end
35+
36+
Data = DataLite
37+
end
38+
end
39+
40+
# :nocov:
41+
# Need to skip test coverage for the rest, because it isn't loaded by ruby 3.2+.
42+
return if RUBY_VERSION >= "3.2.0"
43+
44+
module Net
45+
class IMAP
46+
# DataLite is a temporary substitute for ruby 3.2's +Data+ class. DataLite
47+
# is aliased as Net::IMAP::Data, so that code using it won't need to be
48+
# updated when it is removed.
49+
#
50+
# See {ruby 3.2's documentation for Data}[https://docs.ruby-lang.org/en/3.2/Data.html].
51+
#
52+
# [When running ruby 3.1]
53+
# This class reimplements the API for ruby 3.2's +Data+, and should be
54+
# compatible for nearly all use-cases. This reimplementation <em>will be
55+
# removed</em> in +net-imap+ 0.6, when support for ruby 3.1 is dropped.
56+
#
57+
# _NOTE:_ +net-imap+ no longer supports ruby versions prior to 3.1.
58+
# [When running ruby >= 3.2]
59+
# This class inherits from +Data+ and _only_ defines the methods needed
60+
# for YAML serialization. This will be dropped when +psych+ adds support
61+
# for +Data+.
62+
#
63+
# Some of the code in this class was copied or adapted from the
64+
# {polyfill-data gem}[https://rubygems.org/gems/polyfill-data], by Jim Gay
65+
# and Joel Drapper, under the MIT license terms.
66+
class DataLite
67+
singleton_class.undef_method :new
68+
69+
TYPE_ERROR = "%p is not a symbol nor a string"
70+
ATTRSET_ERROR = "invalid data member: %p"
71+
DUP_ERROR = "duplicate member: %p"
72+
ARITY_ERROR = "wrong number of arguments (given %d, expected %s)"
73+
private_constant :TYPE_ERROR, :ATTRSET_ERROR, :DUP_ERROR, :ARITY_ERROR
74+
75+
# Defines a new Data class.
76+
#
77+
# _NOTE:_ Unlike ruby 3.2's +Data.define+, DataLite.define only supports
78+
# member names which are valid local variable names. Member names can't
79+
# be keywords (e.g: +next+ or +class+) or start with capital letters, "@",
80+
# etc.
81+
def self.define(*args, &block)
82+
members = args.each_with_object({}) do |arg, members|
83+
arg = arg.to_str unless arg in Symbol | String if arg.respond_to?(:to_str)
84+
arg = arg.to_sym if arg in String
85+
arg in Symbol or raise TypeError, TYPE_ERROR % [arg]
86+
arg in %r{=} and raise ArgumentError, ATTRSET_ERROR % [arg]
87+
members.key?(arg) and raise ArgumentError, DUP_ERROR % [arg]
88+
members[arg] = true
89+
end
90+
members = members.keys.freeze
91+
92+
klass = ::Class.new(self)
93+
94+
klass.singleton_class.undef_method :define
95+
klass.define_singleton_method(:members) { members }
96+
97+
def klass.new(*args, **kwargs, &block)
98+
if kwargs.size.positive?
99+
if args.size.positive?
100+
raise ArgumentError, ARITY_ERROR % [args.size, 0]
101+
end
102+
elsif members.size < args.size
103+
expected = members.size.zero? ? 0 : 0..members.size
104+
raise ArgumentError, ARITY_ERROR % [args.size, expected]
105+
else
106+
kwargs = Hash[members.take(args.size).zip(args)]
107+
end
108+
allocate.tap do |instance|
109+
instance.__send__(:initialize, **kwargs, &block)
110+
end.freeze
111+
end
112+
113+
klass.singleton_class.alias_method :[], :new
114+
klass.attr_reader(*members)
115+
116+
# Dynamically defined initializer methods are in an included module,
117+
# rather than directly on DataLite (like in ruby 3.2+):
118+
# * simpler to handle required kwarg ArgumentErrors
119+
# * easier to ensure consistent ivar assignment order (object shape)
120+
# * faster than instance_variable_set
121+
klass.include(Module.new do
122+
if members.any?
123+
kwargs = members.map{"#{_1.name}:"}.join(", ")
124+
params = members.map(&:name).join(", ")
125+
ivars = members.map{"@#{_1.name}"}.join(", ")
126+
attrs = members.map{"attrs[:#{_1.name}]"}.join(", ")
127+
module_eval <<~RUBY, __FILE__, __LINE__ + 1
128+
protected
129+
def initialize(#{kwargs}) #{ivars} = #{params}; freeze end
130+
def marshal_load(attrs) #{ivars} = #{attrs}; freeze end
131+
RUBY
132+
end
133+
end)
134+
135+
klass.module_eval do _1.module_eval(&block) end if block_given?
136+
137+
klass
138+
end
139+
140+
##
141+
# singleton-method: new
142+
# call-seq:
143+
# new(*args) -> instance
144+
# new(**kwargs) -> instance
145+
#
146+
# Constuctor for classes defined with ::define.
147+
#
148+
# Aliased as ::[].
149+
150+
##
151+
# singleton-method: []
152+
# call-seq:
153+
# ::[](*args) -> instance
154+
# ::[](**kwargs) -> instance
155+
#
156+
# Constuctor for classes defined with ::define.
157+
#
158+
# Alias for ::new
159+
160+
##
161+
def members; self.class.members end
162+
def attributes; Hash[members.map {|m| [m, send(m)] }] end
163+
def to_h(&block) attributes.to_h(&block) end
164+
def hash; [self.class, attributes].hash end
165+
def ==(other) self.class == other.class && to_h == other.to_h end
166+
def eql?(other) self.class == other.class && hash == other.hash end
167+
def deconstruct; attributes.values end
168+
169+
def deconstruct_keys(keys)
170+
raise TypeError unless keys.is_a?(Array) || keys.nil?
171+
return attributes if keys&.first.nil?
172+
attributes.slice(*keys)
173+
end
174+
175+
def with(**kwargs)
176+
return self if kwargs.empty?
177+
self.class.new(**attributes.merge(kwargs))
178+
end
179+
180+
def inspect
181+
__inspect_guard__(self) do |seen|
182+
return "#<data #{self.class}:...>" if seen
183+
attrs = attributes.map {|kv| "%s=%p" % kv }.join(", ")
184+
display = ["data", self.class.name, attrs].compact.join(" ")
185+
"#<#{display}>"
186+
end
187+
end
188+
alias_method :to_s, :inspect
189+
190+
private
191+
192+
def initialize_copy(source) super.freeze end
193+
def marshal_dump; attributes end
194+
195+
# Yields +true+ if +obj+ has been seen already, +false+ if it hasn't.
196+
# Marks +obj+ as seen inside the block, so circuler references don't
197+
# recursively trigger a SystemStackError (stack level too deep).
198+
#
199+
# Making circular references inside a Data object _should_ be very
200+
# uncommon, but we'll support them for the sake of completeness.
201+
def __inspect_guard__(obj)
202+
preexisting = Thread.current[:__net_imap_data__inspect__]
203+
Thread.current[:__net_imap_data__inspect__] ||= {}.compare_by_identity
204+
inspect_guard = Thread.current[:__net_imap_data__inspect__]
205+
if inspect_guard.include?(obj)
206+
yield true
207+
else
208+
begin
209+
inspect_guard[obj] = true
210+
yield false
211+
ensure
212+
inspect_guard.delete(obj)
213+
end
214+
end
215+
ensure
216+
unless preexisting.equal?(inspect_guard)
217+
Thread.current[:__net_imap_data__inspect__] = preexisting
218+
end
219+
end
220+
221+
end
222+
223+
end
224+
end
225+
# :nocov:

0 commit comments

Comments
 (0)