From 23465d5a312f86d989ec647522bd3151554a79e4 Mon Sep 17 00:00:00 2001 From: Dave Reisner Date: Sat, 5 Jan 2013 21:47:04 -0500 Subject: unify logic for finding by name fragment --- pulse.cc | 61 ++++++++++++++++++++++++++++--------------------------------- 1 file changed, 28 insertions(+), 33 deletions(-) (limited to 'pulse.cc') diff --git a/pulse.cc b/pulse.cc index d1d9359..ae4ccf2 100644 --- a/pulse.cc +++ b/pulse.cc @@ -93,7 +93,6 @@ static int xstrtol(const char *str, long *out) { return 0; } - } // anonymous namespace PulseClient::PulseClient(string client_name) : @@ -152,23 +151,11 @@ Card* PulseClient::GetCard(const uint32_t& index) { Card* PulseClient::GetCard(const string& name) { long val; vector res; - if (xstrtol(name.c_str(), &val) == 0) return GetCard(val); - - for (Card& card : cards_) { - if (card.name_.find(name) != string::npos) res.push_back(&card); + if (xstrtol(name.c_str(), &val) == 0) { + return GetCard(val); + } else { + return find_fuzzy(cards_, name); } - - switch (res.size()) { - case 0: - return nullptr; - case 1: - break; - default: - warnx("warning: ambiguous result for '%s', using '%s'", - name.c_str(), res[0]->name_.c_str()); - } - - return res[0]; } Card* PulseClient::GetCard(const Device& device) { @@ -189,23 +176,11 @@ Device* PulseClient::get_device(vector& devices, Device* PulseClient::get_device(vector& devices, const string& name) { long val; vector res; - if (xstrtol(name.c_str(), &val) == 0) return get_device(devices, val); - - for (Device& device : devices) { - if (device.name_.find(name) != string::npos) res.push_back(&device); + if (xstrtol(name.c_str(), &val) == 0) { + return get_device(devices, val); + } else { + return find_fuzzy(devices, name); } - - switch (res.size()) { - case 0: - return nullptr; - case 1: - break; - default: - warnx("warning: ambiguous result for '%s', using '%s'", - name.c_str(), res[0]->name_.c_str()); - } - - return res[0]; } Device* PulseClient::GetDevice(const uint32_t& index, enum DeviceType type) { @@ -289,6 +264,26 @@ void PulseClient::mainloop_iterate(pa_operation* op) { } } +template +T* PulseClient::find_fuzzy(vector haystack, const string& needle) { + vector res; + + for (T& item : haystack) { + if (item.name_.find(needle) != string::npos) res.push_back(&item); + } + + switch (res.size()) { + case 0: + return nullptr; + case 1: + break; + default: + warnx("warning: ambiguous result for '%s', using '%s'", + needle.c_str(), res[0]->name_.c_str()); + } + return res[0]; +} + void PulseClient::populate_cards() { cards_.clear(); pa_operation* op = pa_context_get_card_info_list(context_, -- cgit v1.2.3