bitswitch 0.0.1 → 0.0.2
Sign up to get free protection for your applications and to get access to all the features.
- data/README.md +1 -1
- data/lib/bitswitch.rb +71 -1
- data/lib/bitswitch/version.rb +1 -1
- metadata +1 -1
data/README.md
CHANGED
data/lib/bitswitch.rb
CHANGED
@@ -1,27 +1,97 @@
|
|
1
1
|
class BitSwitch
|
2
|
-
|
2
|
+
|
3
|
+
def initialize(n = 0, labels = {})
|
4
|
+
|
5
|
+
if n.is_a?(Hash)
|
6
|
+
|
7
|
+
# Set default values
|
8
|
+
@labels = {}
|
9
|
+
@val = 0
|
10
|
+
|
11
|
+
# Loop through the hash and set the switches
|
12
|
+
i=0; n.each do |label, tf|
|
13
|
+
self[i] = tf ? 1 : 0
|
14
|
+
@labels[i] = label
|
15
|
+
i += 1
|
16
|
+
end
|
17
|
+
|
18
|
+
# Return the BitSwitch object
|
19
|
+
return self
|
20
|
+
end
|
21
|
+
|
22
|
+
# Set labels and initial number
|
23
|
+
@labels = labels
|
3
24
|
@val = n
|
4
25
|
end
|
5
26
|
|
27
|
+
# Set a bit
|
6
28
|
def []=(bit, val)
|
7
29
|
val = val > 0
|
30
|
+
|
31
|
+
# If a string representation of a bit was provided get the numerical
|
32
|
+
bit = @labels.invert[bit] if bit.is_a?(String)
|
33
|
+
|
34
|
+
# If nil return false
|
35
|
+
return false if bit.nil?
|
8
36
|
|
37
|
+
# Set/Unset the bits
|
9
38
|
@val |= 2 ** bit if val
|
10
39
|
@val &= ~(2 ** bit) if !val && self[bit]
|
40
|
+
|
41
|
+
# Return self
|
42
|
+
return self
|
11
43
|
end
|
12
44
|
|
45
|
+
# Check a bit status
|
13
46
|
def [](bit)
|
47
|
+
|
48
|
+
# If a string representation of a bit was provided get the numerical
|
49
|
+
bit = @labels.invert[bit] if bit.is_a?(String)
|
50
|
+
|
51
|
+
# If nil return false
|
52
|
+
return false if bit.nil?
|
53
|
+
|
54
|
+
# Check if the bit it set
|
14
55
|
(2 ** bit) & @val > 0
|
15
56
|
end
|
16
57
|
|
58
|
+
# Set an integer
|
17
59
|
def set=(n)
|
18
60
|
return false unless n.is_a?(Fixnum)
|
19
61
|
@val = n
|
20
62
|
end
|
63
|
+
|
64
|
+
def labels=(hash = {}, reset = false)
|
65
|
+
|
66
|
+
# If reset is false then merge the labels
|
67
|
+
return @labels.merge(hash) unless reset
|
68
|
+
|
69
|
+
# Set a whole new label hash
|
70
|
+
@labels = hash
|
71
|
+
end
|
21
72
|
|
73
|
+
# Convert to integer
|
22
74
|
def to_i
|
23
75
|
@val
|
24
76
|
end
|
77
|
+
|
78
|
+
# Convert to hash
|
79
|
+
def to_hash
|
80
|
+
|
81
|
+
# Raise an error if no labels are set
|
82
|
+
raise StandardError, "No labels were set!" if @labels.empty?
|
83
|
+
|
84
|
+
# Prepare new hash
|
85
|
+
serialized = Hash.new
|
86
|
+
|
87
|
+
# Loop through the labels
|
88
|
+
@labels.each do |bit, label|
|
89
|
+
serialized[label] = self[bit]
|
90
|
+
end
|
91
|
+
|
92
|
+
# Return the serialized BitSwitch
|
93
|
+
serialized
|
94
|
+
end
|
25
95
|
end
|
26
96
|
|
27
97
|
class Fixnum
|
data/lib/bitswitch/version.rb
CHANGED