Debian Codegraph @

ruby/lib/types/strings.rb

raw
1 # Licensed to the Apache Software Foundation (ASF) under one
2 # or more contributor license agreements. See the NOTICE file
3 # distributed with this work for additional information
4 # regarding copyright ownership. The ASF licenses this file
5 # to you under the Apache License, Version 2.0 (the
6 # "License"); you may not use this file except in compliance
7 # with the License. You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing,
12 # software distributed under the License is distributed on an
13 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 # KIND, either express or implied. See the License for the
15 # specific language governing permissions and limitations
16 # under the License.
17
18
19 module Qpid::Proton::Types
20
21 # @private
22 def self.is_valid_utf?(value)
23 # In Ruby 1.9+ we have encoding methods that can check the content of
24 # the string, so use them to see if what we have is unicode. If so,
25 # good! If not, then just treat is as binary.
26 #
27 # No such thing in Ruby 1.8. So there we need to use Iconv to try and
28 # convert it to unicode. If it works, good! But if it raises an
29 # exception then we'll treat it as binary.
30 if RUBY_VERSION < "1.9"
31 return true if value.isutf8
32 return false
33 else
34 return true if (value.encoding == "UTF-8" ||
35 value.encode("UTF-8").valid_encoding?)
36
37 return false
38 end
39 end
40
41 # UTFString lets an application explicitly state that a
42 # string of characters is to be UTF-8 encoded.
43 #
44 class UTFString < ::String
45
46 def initialize(value)
47 if !Qpid::Proton::Types.is_valid_utf?(value)
48 raise RuntimeError.new("invalid UTF string")
49 end
50
51 super(value)
52 end
53
54 end
55
56 # BinaryString lets an application explicitly declare that
57 # a string value represents arbitrary data.
58 #
59 class BinaryString < ::String; end
60
61 end