File: immutable_struct.rb

package info (click to toggle)
ruby-concurrent 1.1.6%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 30,284 kB
  • sloc: ruby: 30,875; java: 6,117; javascript: 1,114; ansic: 288; makefile: 10; sh: 6
file content (101 lines) | stat: -rw-r--r-- 2,228 bytes parent folder | download | duplicates (2)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
require 'concurrent/synchronization/abstract_struct'
require 'concurrent/synchronization'

module Concurrent

  # A thread-safe, immutable variation of Ruby's standard `Struct`.
  #
  # @see http://ruby-doc.org/core-2.2.0/Struct.html Ruby standard library `Struct`
  module ImmutableStruct
    include Synchronization::AbstractStruct

    def self.included(base)
      base.safe_initialization!
    end

    # @!macro struct_values
    def values
      ns_values
    end

    alias_method :to_a, :values

    # @!macro struct_values_at
    def values_at(*indexes)
      ns_values_at(indexes)
    end

    # @!macro struct_inspect
    def inspect
      ns_inspect
    end

    alias_method :to_s, :inspect

    # @!macro struct_merge
    def merge(other, &block)
      ns_merge(other, &block)
    end

    # @!macro struct_to_h
    def to_h
      ns_to_h
    end

    # @!macro struct_get
    def [](member)
      ns_get(member)
    end

    # @!macro struct_equality
    def ==(other)
      ns_equality(other)
    end

    # @!macro struct_each
    def each(&block)
      return enum_for(:each) unless block_given?
      ns_each(&block)
    end

    # @!macro struct_each_pair
    def each_pair(&block)
      return enum_for(:each_pair) unless block_given?
      ns_each_pair(&block)
    end

    # @!macro struct_select
    def select(&block)
      return enum_for(:select) unless block_given?
      ns_select(&block)
    end

    private

    # @!visibility private
    def initialize_copy(original)
      super(original)
      ns_initialize_copy
    end

    # @!macro struct_new
    def self.new(*args, &block)
      clazz_name = nil
      if args.length == 0
        raise ArgumentError.new('wrong number of arguments (0 for 1+)')
      elsif args.length > 0 && args.first.is_a?(String)
        clazz_name = args.shift
      end
      FACTORY.define_struct(clazz_name, args, &block)
    end

    FACTORY = Class.new(Synchronization::LockableObject) do
      def define_struct(name, members, &block)
        synchronize do
          Synchronization::AbstractStruct.define_struct_class(ImmutableStruct, Synchronization::Object, name, members, &block)
        end
      end
    end.new
    private_constant :FACTORY
  end
end