File: type.rb

package info (click to toggle)
ruby-dbus 0.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 776 kB
  • sloc: ruby: 6,584; xml: 225; sh: 38; makefile: 8
file content (424 lines) | stat: -rw-r--r-- 12,730 bytes parent folder | download
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# frozen_string_literal: true

# dbus/type.rb - module containing low-level D-Bus data type information
#
# This file is part of the ruby-dbus project
# Copyright (C) 2007 Arnaud Cornet and Paul van Tilburg
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License, version 2.1 as published by the Free Software Foundation.
# See the file "COPYING" for the exact licensing terms.

module DBus
  # Like a {Signature} but containing only a single complete type.
  #
  # For documentation purposes only.
  class SingleCompleteType < String; end

  # Zero or more {SingleCompleteType}s; its own type code is "g".
  # For example "ssv" for a method taking two Strings and a Variant/
  #
  # For documentation purposes only.
  class Signature < String; end

  # Similar to {Signature} but for {DBus::Object.define_method},
  # contains names and direction of the parameters.
  # For example "in query:s, in case_sensitive:b, out results:ao".
  #
  # For documentation purposes only.
  class Prototype < String; end

  # Represents the D-Bus types.
  #
  # Corresponds to {SingleCompleteType}.
  # Instances are immutable/frozen once fully constructed.
  #
  # See also {DBus::Data::Signature} which is "type on the wire".
  class Type
    # Mapping from type number to name and alignment.
    TYPE_MAPPING = {
      0 => ["INVALID", nil],
      "y" => ["BYTE", 1],
      "b" => ["BOOLEAN", 4],
      "n" => ["INT16", 2],
      "q" => ["UINT16", 2],
      "i" => ["INT32", 4],
      "u" => ["UINT32", 4],
      "x" => ["INT64", 8],
      "t" => ["UINT64", 8],
      "d" => ["DOUBLE", 8],
      "r" => ["STRUCT", 8],
      "a" => ["ARRAY", 4],
      "v" => ["VARIANT", 1],
      "o" => ["OBJECT_PATH", 4],
      "s" => ["STRING", 4],
      "g" => ["SIGNATURE", 1],
      "e" => ["DICT_ENTRY", 8],
      "h" => ["UNIX_FD", 4]
    }.freeze
    # Defines the set of constants
    TYPE_MAPPING.each_pair do |key, value|
      Type.const_set(value.first, key)
    end

    # Exception raised when an unknown/incorrect type is encountered.
    class SignatureException < Exception
    end

    # Formerly this was a Module and there was a DBus::Type::Type class
    # but the class got too prominent to keep its double double name.
    # This is for backward compatibility.
    Type = self # rubocop:disable Naming/ConstantName

    # @return [String] the signature type character, eg "s" or "e".
    attr_reader :sigtype
    # @return [Array<Type>] contained member types.
    attr_reader :members

    # Use {DBus.type} instead, because this allows constructing
    # incomplete or invalid types, for backward compatibility.
    #
    # @param abstract [Boolean] allow abstract types "r" and "e"
    #   (Enabled for internal usage by {Parser}.)
    def initialize(sigtype, abstract: false)
      if !TYPE_MAPPING.keys.member?(sigtype)
        case sigtype
        when ")"
          raise SignatureException, "STRUCT unexpectedly closed: )"
        when "}"
          raise SignatureException, "DICT_ENTRY unexpectedly closed: }"
        else
          raise SignatureException, "Unknown type code #{sigtype.inspect}"
        end
      end

      unless abstract
        case sigtype
        when STRUCT
          raise SignatureException, "Abstract STRUCT, use \"(...)\" instead of \"#{STRUCT}\""
        when DICT_ENTRY
          raise SignatureException, "Abstract DICT_ENTRY, use \"{..}\" instead of \"#{DICT_ENTRY}\""
        end
      end

      @sigtype = sigtype.freeze
      @members = [] # not frozen yet, Parser#parse_one or Factory will do it
      freeze
    end

    # A Type is equal to
    # - another Type with the same string representation
    # - a String ({SingleCompleteType}) describing the type
    def ==(other)
      case other
      when ::String
        to_s == other
      else
        eql?(other)
      end
    end

    # A Type is eql? to
    # - another Type with the same string representation
    #
    # Hash key equality
    # See https://ruby-doc.org/core-3.0.0/Object.html#method-i-eql-3F
    def eql?(other)
      return false unless other.is_a?(Type)

      @sigtype == other.sigtype && @members == other.members
    end

    # Return the required alignment for the type.
    def alignment
      TYPE_MAPPING[@sigtype].last
    end

    # Return a string representation of the type according to the
    # D-Bus specification.
    def to_s
      case @sigtype
      when STRUCT
        "(#{@members.collect(&:to_s).join})"
      when ARRAY
        "a#{child}"
      when DICT_ENTRY
        "{#{@members.collect(&:to_s).join}}"
      else
        @sigtype.chr
      end
    end

    # Add a new member type _item_.
    # @param item [Type]
    def <<(item)
      raise ArgumentError unless item.is_a?(Type)

      if ![STRUCT, ARRAY, DICT_ENTRY].member?(@sigtype)
        raise SignatureException
      end
      raise SignatureException if @sigtype == ARRAY && !@members.empty?

      if @sigtype == DICT_ENTRY
        case @members.size
        when 2
          raise SignatureException,
                "DICT_ENTRY must have 2 subtypes, found 3 or more: #{@members.inspect} << #{item.inspect}"
        when 0
          if [STRUCT, ARRAY, DICT_ENTRY, VARIANT].member?(item.sigtype)
            raise SignatureException, "DICT_ENTRY key must be basic (non-container)"
          end
        end
      end
      @members << item
    end

    # Return the first contained member type.
    def child
      @members[0]
    end

    def inspect
      s = TYPE_MAPPING[@sigtype].first
      if [STRUCT, ARRAY, DICT_ENTRY].member?(@sigtype)
        s += ": #{@members.inspect}"
      end
      s
    end

    # = D-Bus type parser class
    #
    # Helper class to parse a type signature in the protocol.
    # @api private
    class Parser
      # Create a new parser for the given _signature_.
      # @param signature [Signature]
      def initialize(signature)
        @signature = signature
        if signature.size > 255
          msg = "Potential signature is longer than 255 characters (#{@signature.size}): #{@signature}"
          raise SignatureException, msg
        end

        @idx = 0
      end

      # Returns the next character from the signature.
      def nextchar
        c = @signature[@idx]
        @idx += 1
        c
      end

      # Parse one character _char_ of the signature.
      # @param for_array [Boolean] are we parsing an immediate child of an ARRAY
      # @return [Type]
      def parse_one(char, for_array: false)
        res = nil
        case char
        when "a"
          res = Type.new(ARRAY)
          char = nextchar
          raise SignatureException, "Empty ARRAY in #{@signature}" if char.nil?

          child = parse_one(char, for_array: true)
          res << child
        when "("
          res = Type.new(STRUCT, abstract: true)
          while (char = nextchar) && char != ")"
            res << parse_one(char)
          end
          raise SignatureException, "STRUCT not closed in #{@signature}" if char.nil?
          raise SignatureException, "Empty STRUCT in #{@signature}" if res.members.empty?
        when "{"
          raise SignatureException, "DICT_ENTRY not an immediate child of an ARRAY" unless for_array

          res = Type.new(DICT_ENTRY, abstract: true)

          # key type, value type
          2.times do |i|
            char = nextchar
            raise SignatureException, "DICT_ENTRY not closed in #{@signature}" if char.nil?

            raise SignatureException, "DICT_ENTRY must have 2 subtypes, found #{i} in #{@signature}" if char == "}"

            res << parse_one(char)
          end

          # closing "}"
          char = nextchar
          raise SignatureException, "DICT_ENTRY not closed in #{@signature}" if char.nil?

          raise SignatureException, "DICT_ENTRY must have 2 subtypes, found 3 or more in #{@signature}" if char != "}"
        else
          res = Type.new(char)
        end
        res.members.freeze
        res
      end

      # Parse the entire signature, return a DBus::Type object.
      # @return [Array<Type>]
      def parse
        @idx = 0
        ret = []
        while (c = nextchar)
          ret << parse_one(c)
        end
        ret.freeze
      end

      # Parse one {SingleCompleteType}
      # @return [Type]
      def parse1
        c = nextchar
        raise SignatureException, "Empty signature, expecting a Single Complete Type" if c.nil?

        t = parse_one(c)
        raise SignatureException, "Has more than a Single Complete Type: #{@signature}" unless nextchar.nil?

        t.freeze
      end
    end

    class Factory
      # @param type [Type,SingleCompleteType,Class]
      # @see from_plain_class
      # @return [Type] (frozen)
      def self.make_type(type)
        case type
        when Type
          type
        when String
          DBus.type(type)
        when Class
          from_plain_class(type)
        else
          msg = "Expecting DBus::Type, DBus::SingleCompleteType(aka ::String), or Class, got #{type.inspect}"
          raise ArgumentError, msg
        end
      end

      # Make a {Type} corresponding to some plain classes:
      # - String
      # - Float
      # - DBus::ObjectPath
      # - DBus::Signature, DBus::SingleCompleteType
      # @param klass [Class]
      # @return [Type] (frozen)
      def self.from_plain_class(klass)
        @signature_type ||= DBus.type(SIGNATURE)
        @class_to_type ||= {
          DBus::ObjectPath => DBus.type(OBJECT_PATH),
          DBus::Signature => @signature_type,
          DBus::SingleCompleteType => @signature_type,
          String => DBus.type(STRING),
          Float => DBus.type(DOUBLE)
        }
        t = @class_to_type[klass]
        raise ArgumentError, "Cannot convert plain class #{klass} to a D-Bus type" if t.nil?

        t
      end
    end

    # Syntactic helper for constructing an array Type.
    # You may be looking for {Data::Array} instead.
    # @example
    #   t = Type::Array[Type::INT16]
    class ArrayFactory < Factory
      # @param member_type [Type,SingleCompleteType]
      # @return [Type] (frozen)
      def self.[](member_type)
        t = Type.new(ARRAY)
        t << make_type(member_type)
        t.members.freeze
        t
      end
    end

    # @example
    #   t = Type::Array[Type::INT16]
    Array = ArrayFactory

    # Syntactic helper for constructing a hash Type.
    # You may be looking for {Data::Array} and {Data::DictEntry} instead.
    # @example
    #   t = Type::Hash[Type::STRING, Type::VARIANT]
    class HashFactory < Factory
      # @param key_type [Type,SingleCompleteType]
      # @param value_type [Type,SingleCompleteType]
      # @return [Type] (frozen)
      def self.[](key_type, value_type)
        t = Type.new(ARRAY)
        de = Type.new(DICT_ENTRY, abstract: true)
        de << make_type(key_type)
        de << make_type(value_type)
        de.members.freeze
        t << de
        t.members.freeze
        t
      end
    end

    # @example
    #   t = Type::Hash[Type::INT16]
    Hash = HashFactory

    # Syntactic helper for constructing a struct Type.
    # You may be looking for {Data::Struct} instead.
    # @example
    #   t = Type::Struct[Type::INT16, Type::STRING]
    class StructFactory < Factory
      # @param member_types [::Array<Type,SingleCompleteType>]
      # @return [Type] (frozen)
      def self.[](*member_types)
        raise ArgumentError if member_types.empty?

        t = Type.new(STRUCT, abstract: true)
        member_types.each do |mt|
          t << make_type(mt)
        end
        t.members.freeze
        t
      end
    end

    # @example
    #   t = Type::Struct[Type::INT16, Type::STRING]
    Struct = StructFactory
  end

  # shortcuts

  # Parse a String to a valid {DBus::Type}.
  # This is prefered to {Type#initialize} which allows
  # incomplete or invalid types.
  # @param string_type [SingleCompleteType]
  # @return [DBus::Type] (frozen)
  # @raise SignatureException
  def type(string_type)
    Type::Parser.new(string_type).parse1
  end
  module_function :type

  # Parse a String to zero or more {DBus::Type}s.
  # @param string_type [Signature]
  # @return [Array<DBus::Type>] (frozen)
  # @raise SignatureException
  def types(string_type)
    Type::Parser.new(string_type).parse
  end
  module_function :types

  # Make an explicit [Type, value] pair
  # @param string_type [SingleCompleteType]
  # @param value [::Object]
  # @return [Array(DBus::Type::Type,::Object)]
  # @deprecated Use {Data::Variant#initialize} instead
  def variant(string_type, value)
    Data::Variant.new(value, member_type: string_type)
  end
  module_function :variant
end