Allow to start/stop resources on a per-request basis
authorEnrico Zini <enrico@enricozini.org>
Tue, 14 Jul 2009 16:04:29 +0000 (17:04 +0100)
committerEnrico Zini <enrico@enricozini.org>
Tue, 14 Jul 2009 16:04:29 +0000 (17:04 +0100)
vala/registry.vala

index c420972949379ecad36833e94d92285dc7ae66d0..2c122bffe1ccfcf57db5f83721fb63ac997edbf2 100644 (file)
@@ -40,6 +40,11 @@ public abstract class Resource : Object {
 
 public abstract class Service : Resource {
        protected bool is_started = false;
+       protected HashMap<string, int> requests;
+
+       construct {
+               requests = new HashMap<string, int>(str_hash, str_equal);
+       }
 
        public signal void started();
        public signal void stopped();
@@ -63,6 +68,52 @@ public abstract class Service : Resource {
                is_started = false;
                stopped();
        }
+
+       /**
+        * Request a resource using the given ID.
+        *
+        * If it is the first time the resource is requested, start it and
+        * return true. Else, take note of the request and return false.
+        *
+        * If a resource is requested multiple times with the same ID, it will
+        * need to be released multiple times with that ID.
+        */
+       public bool request(string id)
+       {
+               bool res = (requests.size == 0);
+               if (id in requests)
+                       requests[id] = requests[id] + 1;
+               else
+                       requests.set(id, 1);
+               if (res) start();
+               return res;
+       }
+
+       /**
+        * Release a resource using the given ID.
+        *
+        * If after the call nothing is requesting the resource, stop it and
+        * return true. Else, take note of the release and return false.
+        *
+        * If a resource is requested multiple times with the same ID, it will
+        * need to be released multiple times with that ID.
+        */
+       public bool release(string id)
+       {
+               if (id in requests)
+               {
+                       if (requests[id] > 0)
+                               requests[id] = requests[id] - 1;
+                       else
+                               requests.remove(id);
+               } else {
+                       return false;
+               }
+               if (requests.size > 0)
+                       return false;
+               stop();
+               return true;
+       }
 }
 
 // class Service(Resource):