# File lib/uuid.rb, line 176
176:   def generate(format = :default)
177:     template = FORMATS[format]
178: 
179:     raise ArgumentError, "invalid UUID format #{format.inspect}" unless template
180: 
181:     # The clock must be monotonically increasing. The clock resolution is at
182:     # best 100 ns (UUID spec), but practically may be lower (on my setup,
183:     # around 1ms). If this method is called too fast, we don't have a
184:     # monotonically increasing clock, so the solution is to just wait.
185:     #
186:     # It is possible for the clock to be adjusted backwards, in which case we
187:     # would end up blocking for a long time. When backward clock is detected,
188:     # we prevent duplicates by asking for a new sequence number and continue
189:     # with the new clock.
190: 
191:     clock = @mutex.synchronize do
192:       clock = (Time.new.to_f * CLOCK_MULTIPLIER).to_i & 0xFFFFFFFFFFFFFFF0
193: 
194:       if clock > @last_clock then
195:         @drift = 0
196:         @last_clock = clock
197:       elsif clock == @last_clock then
198:         drift = @drift += 1
199: 
200:         if drift < 10000 then
201:           @last_clock += 1
202:         else
203:           Thread.pass
204:           nil
205:         end
206:       else
207:         next_sequence
208:         @last_clock = clock
209:       end
210:     end until clock
211: 
212:     template % [
213:         clock        & 0xFFFFFFFF,
214:        (clock >> 32) & 0xFFFF,
215:       ((clock >> 48) & 0xFFFF | VERSION_CLOCK),
216:       @sequence      & 0xFFFF,
217:       @mac           & 0xFFFFFFFFFFFF
218:     ]
219:   end