Module: MCPClient::DeepCopy
- Included in:
- Prompt, Resource, ResourceTemplate, Tool
- Defined in:
- lib/mcp_client/deep_copy.rb
Overview
Deep copies for the objects a transport hands out of its caches: a caller may change what it received without changing what is cached. Copies every instance variable but the transport reference (@server).
Class Method Summary collapse
-
.copy(value) ⇒ Object
A copy sharing no mutable structure with the input.
-
.shallow_copy(value) ⇒ Object
An empty container for a hash or array, else the leaf copy DeepCopy.copy would have made.
Instance Method Summary collapse
Class Method Details
.copy(value) ⇒ Object
Returns a copy sharing no mutable structure with the input.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/mcp_client/deep_copy.rb', line 10 def self.copy(value) # Iterative: a peer-supplied document may be nested deeper than the # Ruby stack allows, and a copy must never be what overflows it. root = shallow_copy(value) pending = [[value, root]] until pending.empty? source, target = pending.pop case source when Hash then source.each { |k, v| pending << [v, target[shallow_copy(k)] = shallow_copy(v)] } when Array then source.each_with_index { |v, i| pending << [v, target[i] = shallow_copy(v)] } end end root end |
.shallow_copy(value) ⇒ Object
Returns an empty container for a hash or array, else the leaf copy copy would have made.
28 29 30 31 32 33 34 35 36 |
# File 'lib/mcp_client/deep_copy.rb', line 28 def self.shallow_copy(value) case value when Hash then {} when Array then Array.new(value.size) when String then value.frozen? ? value : value.dup when DeepCopy then value.dup else value end end |
Instance Method Details
#initialize_copy(source) ⇒ void
This method returns an undefined value.
40 41 42 43 44 45 46 47 |
# File 'lib/mcp_client/deep_copy.rb', line 40 def initialize_copy(source) super source.instance_variables.each do |ivar| next if ivar == :@server instance_variable_set(ivar, DeepCopy.copy(source.instance_variable_get(ivar))) end end |