From a503b8391ef1fbad501bb362575c4d0d752ebc7e Mon Sep 17 00:00:00 2001 From: Richard Ramsden Date: Sat, 19 May 2012 15:47:50 -0700 Subject: [PATCH] add method to give unique ids for x11 resources X11 Protocol expects clients to track unique identifiers in order to reduce network traffic. This reduces network traffic because when you create a new resource say a window the X11 server doesn't have to reply with the ID of the newly created resource. This makes the X11 protocol extremely fast since most requests the server doesn't need to reply to a message. In the first packet returned from X11 they give you a resource-id-mask and a resource-id-base. You can use these values to generate a unique id for X11. --- lib/X11/display.rb | 13 +++++++++++++ test/core_test.rb | 15 +++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 test/core_test.rb diff --git a/lib/X11/display.rb b/lib/X11/display.rb index bc06524..2fa91ba 100644 --- a/lib/X11/display.rb +++ b/lib/X11/display.rb @@ -31,6 +31,19 @@ module X11 end end + ## + # The resource-id-mask contains a single contiguous set of bits (at least 18). + # The client allocates resource IDs for types WINDOW, PIXMAP, CURSOR, FONT, + # GCONTEXT, and COLORMAP by choosing a value with only some subset of these + # bits set and ORing it with resource-id-base. + + def new_id + id = (@xid_next ||= 0) + @xid_next += 1 + + (id & @internal.resource_id_mask) | @internal.resource_id_base + end + private def authorize(host, family, display_id) diff --git a/test/core_test.rb b/test/core_test.rb new file mode 100644 index 0000000..68852d7 --- /dev/null +++ b/test/core_test.rb @@ -0,0 +1,15 @@ +require File.expand_path('../helper', __FILE__) + +describe X11 do + describe X11::Display do + before(:each) do + @display = X11::Display.new + end + + it "should generate a unique id" do + collection = 1000.times.collect { @display.new_id } + expected = collection.size + collection.uniq.size.must_equal expected + end + end +end