diff --git a/casbin/config/config.cpp b/casbin/config/config.cpp index bcf66fc5..0a78d4a7 100644 --- a/casbin/config/config.cpp +++ b/casbin/config/config.cpp @@ -25,6 +25,7 @@ #include #include + #include "./config.h" #include "../exception/io_exception.h" #include "../exception/illegal_argument_exception.h" @@ -38,7 +39,7 @@ mutex Config::mtx_lock; /** * addConfig adds a new section->key:value to the configuration. */ -bool Config :: AddConfig(string section, string option, string value) { +bool Config :: AddConfig(string section, string& option, string& value) { if (!section.compare("")) section = DEFAULT_SECTION; bool ok = data[section].find(option) != data[section].end(); @@ -46,12 +47,12 @@ bool Config :: AddConfig(string section, string option, string value) { return !ok; } -void Config :: Parse(string f_name) { +void Config :: Parse(string& f_name) { mtx_lock.lock(); ifstream infile; try { infile.open(f_name); - } catch (const ifstream::failure e) { + } catch (const ifstream::failure& e) { mtx_lock.unlock(); throw IOException("Cannot open file."); } @@ -73,18 +74,19 @@ void Config :: ParseBuffer(istream* buf){ else break; line = Trim(line); - if (line.find(DEFAULT_COMMENT)==0) + if (line.compare(DEFAULT_COMMENT)==0) continue; - else if (line.find(DEFAULT_COMMENT_SEM)==0) + else if (line.compare(DEFAULT_COMMENT_SEM)==0) continue; - else if (line.find("[")==0 && EndsWith(line, string("]"))) + else if (line.compare("[")==0 && EndsWith(line, string("]"))) section = line.substr(1, line.length() - 2); else { - vector option_val = Split(line, string("="), 2); + vector option_val = Split(line, string("=")); if (option_val.size() != 2) { - char* error = new char; - sprintf(error, "parse the content error : line %d , %s = ? ", line_num, option_val[0].c_str()); - throw IllegalArgumentException(string(error)); + //char* error = new char; + string error; + sprintf(const_cast( error.data() ), "parse the content error : line %d , %s = ? ", line_num, option_val[0].c_str()); + throw IllegalArgumentException(error); } string option = Trim(option_val[0]); string value = Trim(option_val[1]); @@ -111,30 +113,31 @@ shared_ptr Config :: NewConfig(string conf_name) { * @param text the model text. * @return the constructor of Config. */ -shared_ptr Config :: NewConfigFromText(string text) { +shared_ptr Config :: NewConfigFromText(string& text) { shared_ptr c(new Config); stringstream stream(text); c->ParseBuffer(&stream); return c; } -bool Config :: GetBool(string key) { +bool Config :: GetBool(string& key) { return Get(key).compare("true")==0; } -int Config :: GetInt(string key) { +int Config :: GetInt(string& key) { return atoi(Get(key).c_str()); } -float Config :: GetFloat(string key) { - return float(atof(Get(key).c_str())); +float Config :: GetFloat(string& key) { + return static_cast( atof(Get(key).c_str()) ); } -string Config :: GetString(string key) { + +string Config :: GetString(const string& key) { return Get(key); } -vector Config :: GetStrings(string key) { +vector Config :: GetStrings(string& key) { string v = Get(key); if (!v.compare("")) { vector empty; @@ -143,7 +146,7 @@ vector Config :: GetStrings(string key) { return Split(v,string(",")); } -void Config :: Set(string key, string value) { +void Config :: Set(string key, string& value) { mtx_lock.lock(); if (key.length() == 0) { mtx_lock.unlock(); @@ -166,6 +169,7 @@ void Config :: Set(string key, string value) { mtx_lock.unlock(); } + string Config :: Get(string key) { string section; string option; diff --git a/casbin/config/config.h b/casbin/config/config.h index 8f4f9b96..decb3e62 100644 --- a/casbin/config/config.h +++ b/casbin/config/config.h @@ -20,6 +20,7 @@ #include #include #include +#include #include "./config_interface.h" @@ -38,14 +39,14 @@ class Config : public ConfigInterface { /** * addConfig adds a new section->key:value to the configuration. */ - bool AddConfig(string section, string option, string value); + bool AddConfig(string section, string& option, string& value); - void Parse(string f_name); + void Parse(string& f_name); void ParseBuffer(istream* buf); public: - + ~Config()=default; /** * NewConfig create an empty configuration representation from file. * @@ -60,21 +61,21 @@ class Config : public ConfigInterface { * @param text the model text. * @return the constructor of Config. */ - static shared_ptr NewConfigFromText(string text); + static shared_ptr NewConfigFromText(string& text); - bool GetBool(string key); + bool GetBool(string& key); - int GetInt(string key); + int GetInt(string& key); - float GetFloat(string key); + float GetFloat(string& key); - string GetString(string key); + string GetString(const string& key); - vector GetStrings(string key); + vector GetStrings(string& key); - void Set(string key, string value); + void Set(string key, string& value); - string Get(string key); + string Get(string k); }; #endif \ No newline at end of file diff --git a/casbin/config/config_interface.h b/casbin/config/config_interface.h index e1adbab6..da69785f 100644 --- a/casbin/config/config_interface.h +++ b/casbin/config/config_interface.h @@ -24,14 +24,14 @@ using namespace std; class ConfigInterface { public: + virtual ~ConfigInterface()=0; - virtual string GetString(string key) = 0; - virtual vector GetStrings(string key) = 0; - virtual bool GetBool(string key) = 0; - virtual int GetInt(string key) = 0; - virtual float GetFloat(string key) = 0; - virtual void Set(string key, string value) = 0; - + virtual string GetString(const string& key) = 0; + virtual vector GetStrings(string& key) = 0; + virtual bool GetBool(string& key) = 0; + virtual int GetInt(string& key) = 0; + virtual float GetFloat(string& key) = 0; + virtual void Set(string key, string& value) = 0; }; #endif \ No newline at end of file diff --git a/casbin/effect/default_effector.cpp b/casbin/effect/default_effector.cpp index 70f3c987..4bb92ca8 100644 --- a/casbin/effect/default_effector.cpp +++ b/casbin/effect/default_effector.cpp @@ -26,12 +26,12 @@ /** * MergeEffects merges all matching results collected by the enforcer into a single decision. */ -bool DefaultEffector :: MergeEffects(string expr, vector effects, vector results) { +bool DefaultEffector :: MergeEffects(string expr, vector& effects, vector& results) { bool result; if (!expr.compare("some(where (p.eft == allow))")) { result = false; - for(unsigned int index = 0 ; index < effects.size() ; index++){ + for(auto index = 0 ; index < effects.size() ; index++){ if (effects[index] == Effect::Allow) { result = true; break; @@ -39,7 +39,7 @@ bool DefaultEffector :: MergeEffects(string expr, vector effects, vector } } else if (!expr.compare("!some(where (p.eft == deny))")) { result = true; - for(unsigned int index = 0 ; index < effects.size(); index++){ + for(auto index = 0 ; index < effects.size(); index++){ if (effects[index] == Effect::Deny) { result = false; break; @@ -47,7 +47,7 @@ bool DefaultEffector :: MergeEffects(string expr, vector effects, vector } } else if (!expr.compare("some(where (p.eft == allow)) && !some(where (p.eft == deny))")) { result = false; - for(unsigned int index = 0 ; index < effects.size(); index++){ + for(auto index = 0 ; index < effects.size(); index++){ if (effects[index] == Effect::Allow) { result = true; } else if (effects[index] == Effect::Deny) { @@ -57,7 +57,7 @@ bool DefaultEffector :: MergeEffects(string expr, vector effects, vector } } else if (!expr.compare("priority(p.eft) || deny")) { result = false; - for(unsigned int index = 0 ; index < effects.size(); index++){ + for(auto index = 0 ; index < effects.size(); index++){ if (effects[index] != Effect::Indeterminate) { if (effects[index] == Effect::Allow) { result = true; diff --git a/casbin/effect/default_effector.h b/casbin/effect/default_effector.h index 876dcc6e..eb28cf52 100644 --- a/casbin/effect/default_effector.h +++ b/casbin/effect/default_effector.h @@ -24,11 +24,11 @@ */ class DefaultEffector : public Effector{ public: - + ~DefaultEffector()=default; /** * MergeEffects merges all matching results collected by the enforcer into a single decision. */ - bool MergeEffects(string expr, vector effects, vector results); + bool MergeEffects(string expr, vector& effects, vector& results); }; #endif \ No newline at end of file diff --git a/casbin/effect/effector.h b/casbin/effect/effector.h index b628870f..6ea73805 100644 --- a/casbin/effect/effector.h +++ b/casbin/effect/effector.h @@ -37,7 +37,8 @@ class Effector{ * @param results the matcher results of all matched rules. * @return the final effect. */ - virtual bool MergeEffects(string expr, vector effects, vector results) = 0; + virtual bool MergeEffects(string expr, vector& effects, vector& results) = 0; + virtual ~Effector()=0; }; #endif \ No newline at end of file diff --git a/casbin/enforcer.cpp b/casbin/enforcer.cpp index 7cb1deeb..f49bac07 100644 --- a/casbin/enforcer.cpp +++ b/casbin/enforcer.cpp @@ -32,7 +32,7 @@ #include "./util/util.h" // enforce use a custom matcher to decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (matcher, sub, obj, act), use model matcher by default when matcher is "". -bool Enforcer :: enforce(string matcher, Scope scope) { +bool Enforcer :: enforce(string& matcher, Scope scope) { // TODO // defer func() { // if err := recover(); err != nil { @@ -59,13 +59,13 @@ bool Enforcer :: enforce(string matcher, Scope scope) { bool ok = this->model->m.find("g") != this->model->m.end(); if(ok) { - for(unordered_map > :: iterator it = this->model->m["g"].assertion_map.begin() ; it != this->model->m["g"].assertion_map.end() ; it++){ + for(unordered_map > :: iterator it = this->model->m["g"].assertion_map.begin() ; it != this->model->m["g"].assertion_map.end() ; ++it){ shared_ptr rm = it->second->rm; int char_count = int(count(it->second->value.begin(), it->second->value.end(), '_')); int index = int(exp_string.find((it->first)+"(")); if(index != string::npos) exp_string.insert(index+(it->first+"(").length(), "rm, "); - PushPointer(this->func_map.scope, (void *)rm.get(), "rm"); + PushPointer(this->func_map.scope, static_cast(rm.get()), "rm"); this->func_map.AddFunction(it->first, GFunction, char_count + 1); } } @@ -168,8 +168,8 @@ bool Enforcer :: enforce(string matcher, Scope scope) { /** * Enforcer is the default constructor. */ -Enforcer ::Enforcer() { -} +/*Enforcer ::Enforcer() { +}*/ /** * Enforcer initializes an enforcer with a model file and a policy file. @@ -177,7 +177,9 @@ Enforcer ::Enforcer() { * @param model_path the path of the model file. * @param policyFile the path of the policy file. */ -Enforcer :: Enforcer(string model_path, string policy_file): Enforcer(model_path, shared_ptr(new FileAdapter(policy_file))) { +Enforcer :: Enforcer(string& model_path, string& policy_file) + :model_path(model_path), fileAdapter(make_shared(policy_file)) + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { } /** @@ -186,8 +188,9 @@ Enforcer :: Enforcer(string model_path, string policy_file): Enforcer(model_path * @param model_path the path of the model file. * @param adapter the adapter. */ -Enforcer :: Enforcer(string model_path, shared_ptr adapter): Enforcer(shared_ptr(new Model(model_path)), adapter) { - this->model_path = model_path; +Enforcer :: Enforcer(string& model_path, shared_ptr adapter) + :model_path(model_path), model(make_shared(model_path)), adapter(adapter) + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { } /** @@ -196,11 +199,10 @@ Enforcer :: Enforcer(string model_path, shared_ptr adapter): Enforcer(s * @param m the model. * @param adapter the adapter. */ -Enforcer :: Enforcer(shared_ptr m, shared_ptr adapter) { - this->adapter = adapter; - this->watcher = NULL; +Enforcer :: Enforcer(shared_ptr m, shared_ptr adapter) + :model(m), watcher(nullptr), adapter(adapter) + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { - this->model = m; this->model->PrintModel(); this->Initialize(); @@ -215,7 +217,9 @@ Enforcer :: Enforcer(shared_ptr m, shared_ptr adapter) { * * @param m the model. */ -Enforcer ::Enforcer(shared_ptr m): Enforcer(m, NULL) { +Enforcer ::Enforcer(shared_ptr m) + :model(m), adapter(nullptr) + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { } /** @@ -223,7 +227,9 @@ Enforcer ::Enforcer(shared_ptr m): Enforcer(m, NULL) { * * @param model_path the path of the model file. */ -Enforcer ::Enforcer(string model_path): Enforcer(model_path, "") { +Enforcer ::Enforcer(string& model_path) + :model_path(model_path), policy_file("") + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { } /** @@ -233,7 +239,9 @@ Enforcer ::Enforcer(string model_path): Enforcer(model_path, "") { * @param policyFile the path of the policy file. * @param enableLog whether to enable Casbin's log. */ -Enforcer :: Enforcer(string model_path, string policy_file, bool enable_log): Enforcer(model_path, shared_ptr(new FileAdapter(policy_file))) { +Enforcer :: Enforcer(string& model_path, string& policy_file, bool enable_log) + :model_path(model_path), fileAdapter(make_shared(policy_file)) + ,enabled(true), auto_save(true), auto_build_role_links(true), auto_notify_watcher(true) { // e.EnableLog(enable_log); } @@ -264,19 +272,14 @@ void Enforcer :: InitWithModelAndAdapter(shared_ptr m, shared_ptrInitialize(); // Do not initialize the full policy when using a filtered adapter - if(this->adapter != NULL && !this->adapter->IsFiltered()) + if(this->adapter != nullptr && !this->adapter->IsFiltered()) this->LoadPolicy(); } void Enforcer :: Initialize() { - this->rm = shared_ptr(new DefaultRoleManager(10)); + this->rm = make_shared(10); this->eft = shared_ptr(new DefaultEffector()); - this->watcher = NULL; - - this->enabled = true; - this->auto_save = true; - this->auto_build_role_links = true; - this->auto_notify_watcher = true; + this->watcher = nullptr; } // LoadModel reloads the model from the model CONF file. @@ -387,8 +390,9 @@ void Enforcer :: SavePolicy() { if(this->watcher != NULL){ if (IsInstanceOf(this->watcher.get())) { - void* watcher = this->watcher.get(); - ((WatcherEx*)watcher)->UpdateForSavePolicy(this->model.get()); + //void* watcher = this->watcher.get(); + //((WatcherEx*)watcher)->UpdateForSavePolicy(this->model.get()); + static_cast(this->watcher.get())->UpdateForSavePolicy(this->model.get()); } else return this->watcher->Update(); @@ -428,7 +432,7 @@ void Enforcer :: BuildRoleLinks() { } // BuildIncrementalRoleLinks provides incremental build the role inheritance relations. -void Enforcer :: BuildIncrementalRoleLinks(policy_op op, string p_type, vector> rules) { +void Enforcer :: BuildIncrementalRoleLinks(policy_op op,string p_type, vector> rules) { return this->model->BuildIncrementalRoleLinks(this->rm, op, "g", p_type, rules); } diff --git a/casbin/enforcer.h b/casbin/enforcer.h index 0d0334e3..f4926415 100644 --- a/casbin/enforcer.h +++ b/casbin/enforcer.h @@ -23,12 +23,14 @@ #include "./model/function.h" #include "./enforcer_interface.h" #include "./persist/filtered_adapter.h" +#include "./persist/file_adapter/file_adapter.h" // Enforcer is the main interface for authorization enforcement and policy management. class Enforcer : public IEnforcer{ private: string model_path; + string policy_file; shared_ptr model; FunctionMap func_map; vector > user_func_list; @@ -36,6 +38,7 @@ class Enforcer : public IEnforcer{ shared_ptr adapter; shared_ptr watcher; + shared_ptr fileAdapter; bool enabled; bool auto_save; @@ -43,7 +46,7 @@ class Enforcer : public IEnforcer{ bool auto_notify_watcher; // enforce use a custom matcher to decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (matcher, sub, obj, act), use model matcher by default when matcher is "". - bool enforce(string matcher, Scope scope); + bool enforce(string& matcher, Scope scope); public: @@ -52,21 +55,21 @@ class Enforcer : public IEnforcer{ /** * Enforcer is the default constructor. */ - Enforcer(); + Enforcer() = default; /** * Enforcer initializes an enforcer with a model file and a policy file. * * @param model_path the path of the model file. * @param policy_file the path of the policy file. */ - Enforcer(string model_path, string policy_file); + Enforcer(string& model_path, string& policy_file); /** * Enforcer initializes an enforcer with a database adapter. * * @param model_path the path of the model file. * @param adapter the adapter. */ - Enforcer(string model_path, shared_ptr adapter); + Enforcer(string& model_path, shared_ptr adapter); /** * Enforcer initializes an enforcer with a model and a database adapter. * @@ -79,13 +82,13 @@ class Enforcer : public IEnforcer{ * * @param m the model. */ - Enforcer(shared_ptr m); + explicit Enforcer(shared_ptr m); /** * Enforcer initializes an enforcer with a model file. * * @param model_path the path of the model file. */ - Enforcer(string model_path); + explicit Enforcer(string& model_path); /** * Enforcer initializes an enforcer with a model file, a policy file and an enable log flag. * @@ -93,7 +96,7 @@ class Enforcer : public IEnforcer{ * @param policy_file the path of the policy file. * @param enable_log whether to enable Casbin's log. */ - Enforcer(string model_path, string policy_file, bool enable_log); + Enforcer(string& model_path, string& policy_file, bool enable_log); // InitWithFile initializes an enforcer with a model file and a policy file. void InitWithFile(string model_path, string policy_path); // InitWithAdapter initializes an enforcer with a database adapter. @@ -181,7 +184,7 @@ class Enforcer : public IEnforcer{ bool HasPolicy(vector params); bool HasNamedPolicy(string p_type, vector params); bool AddPolicy(vector params); - bool AddPolicies(vector> rules); + bool AddPolicies(vector> rules); bool AddNamedPolicy(string p_type, vector params); bool AddNamedPolicies(string p_type, vector> rules); bool RemovePolicy(vector params); @@ -207,22 +210,22 @@ class Enforcer : public IEnforcer{ /*RBAC API member functions.*/ vector GetRolesForUser(string name, vector domain = {}); vector GetUsersForRole(string name, vector domain = {}); - bool HasRoleForUser(string name, string role); - bool AddRoleForUser(string user, string role); - bool AddRolesForUser(string user, vector roles); - bool AddPermissionForUser(string user, vector permission); - bool DeletePermissionForUser(string user, vector permission); - bool DeletePermissionsForUser(string user); - vector> GetPermissionsForUser(string user); - bool HasPermissionForUser(string user, vector permission); + bool HasRoleForUser(string name, string& role); + bool AddRoleForUser(string& user, string& role); + bool AddRolesForUser(string& user, vector roles); + bool AddPermissionForUser(string& user, vector& permission); + bool DeletePermissionForUser(string user, vector& permission); + bool DeletePermissionsForUser(string& user); + vector> GetPermissionsForUser(string& user); + bool HasPermissionForUser(string& user, vector& permission); vector GetImplicitRolesForUser(string name, vector domain = {}); vector> GetImplicitPermissionsForUser(string user, vector domain = {}); vector GetImplicitUsersForPermission(vector permission); - bool DeleteRoleForUser(string user, string role); - bool DeleteRolesForUser(string user); - bool DeleteUser(string user); - bool DeleteRole(string role); - bool DeletePermission(vector permission); + bool DeleteRoleForUser(string& user, string& role); + bool DeleteRolesForUser(string& user); + bool DeleteUser(string& user); + bool DeleteRole(string& role); + bool DeletePermission(vector& permission); /* Internal API member functions */ bool addPolicy(string sec, string p_type, vector rule); @@ -232,11 +235,11 @@ class Enforcer : public IEnforcer{ bool removeFilteredPolicy(string sec , string p_type , int field_index , vector field_values); /* RBAC API with domains.*/ - vector GetUsersForRoleInDomain(string name, string domain = {}); - vector GetRolesForUserInDomain(string name, string domain = {}); - vector> GetPermissionsForUserInDomain(string user, string domain = {}); - bool AddRoleForUserInDomain(string user, string role, string domain = {}); - bool DeleteRoleForUserInDomain(string user, string role, string domain = {}); + vector GetUsersForRoleInDomain(string name, string& domain); + vector GetRolesForUserInDomain(string name, string& domain); + vector> GetPermissionsForUserInDomain(string& user, string& domain); + bool AddRoleForUserInDomain(string& user, string& role, string& domain); + bool DeleteRoleForUserInDomain(string& user, string& role, string& domain); }; diff --git a/casbin/enforcer_cached.cpp b/casbin/enforcer_cached.cpp index 106ee193..24047f6d 100644 --- a/casbin/enforcer_cached.cpp +++ b/casbin/enforcer_cached.cpp @@ -34,8 +34,8 @@ using namespace std; /** * Enforcer is the default constructor. */ -CachedEnforcer ::CachedEnforcer() { - this->enableCache = true; +CachedEnforcer ::CachedEnforcer() + :enableCache(true) { } /** @@ -44,8 +44,8 @@ CachedEnforcer ::CachedEnforcer() { * @param model_path the path of the model file. * @param policyFile the path of the policy file. */ -CachedEnforcer ::CachedEnforcer(string model_path, string policy_file): Enforcer(model_path, policy_file) { - this->enableCache = true; +CachedEnforcer ::CachedEnforcer(string& model_path, string& policy_file) + :model_path(model_path), policy_path(policy_file), enableCache(true) { } /** @@ -54,8 +54,8 @@ CachedEnforcer ::CachedEnforcer(string model_path, string policy_file): Enforcer * @param model_path the path of the model file. * @param adapter the adapter. */ -CachedEnforcer ::CachedEnforcer(string model_path, shared_ptr adapter): Enforcer(model_path,adapter) { - this->enableCache = true; +CachedEnforcer ::CachedEnforcer(string& model_path, shared_ptr adapter) + :model_path(model_path), adapter(adapter), enableCache(true) { } /** @@ -64,8 +64,8 @@ CachedEnforcer ::CachedEnforcer(string model_path, shared_ptr adapter): * @param m the model. * @param adapter the adapter. */ -CachedEnforcer :: CachedEnforcer(shared_ptr m, shared_ptr adapter): Enforcer(m,adapter) { - this->enableCache = true; +CachedEnforcer :: CachedEnforcer(shared_ptr m, shared_ptr adapter) + :model(m), adapter(adapter), enableCache(true) { } /** @@ -73,8 +73,8 @@ CachedEnforcer :: CachedEnforcer(shared_ptr m, shared_ptr adapte * * @param m the model. */ -CachedEnforcer ::CachedEnforcer(shared_ptr m): Enforcer(m) { - this->enableCache = true; +CachedEnforcer ::CachedEnforcer(shared_ptr m) + :model(m), enableCache(true) { } /** @@ -82,8 +82,8 @@ CachedEnforcer ::CachedEnforcer(shared_ptr m): Enforcer(m) { * * @param model_path the path of the model file. */ -CachedEnforcer ::CachedEnforcer(string model_path): Enforcer(model_path) { - this->enableCache = true; +CachedEnforcer ::CachedEnforcer(string& model_path) + :model_path(model_path), enableCache(true) { } /** @@ -93,18 +93,15 @@ CachedEnforcer ::CachedEnforcer(string model_path): Enforcer(model_path) { * @param policyFile the path of the policy file. * @param enableLog whether to enable Casbin's log. */ -CachedEnforcer :: CachedEnforcer(string model_path, string policy_file, bool enable_log): Enforcer(model_path,policy_file,enable_log) { - this->enableCache = true; +CachedEnforcer :: CachedEnforcer(string& model_path, string& policy_file, bool enable_log) + :Enforcer(model_path,policy_file,enable_log) + ,enableCache(true) { } -CachedEnforcer::CachedEnforcer(const CachedEnforcer& ce):Enforcer(ce){ - this->m = ce.m; - this->enableCache = ce.enableCache; +CachedEnforcer::CachedEnforcer(const CachedEnforcer& ce):Enforcer(ce), m(ce.m), enableCache(ce.enableCache) { } -CachedEnforcer::CachedEnforcer(CachedEnforcer&& ce):Enforcer(ce){ - this->m = move(ce.m); - this->enableCache = ce.enableCache; +CachedEnforcer::CachedEnforcer(CachedEnforcer&& ce):Enforcer(ce), m(move(ce.m)), enableCache(ce.enableCache) { } @@ -143,13 +140,13 @@ bool CachedEnforcer ::Enforce(Scope scope) { // Enforce with a vector param,decides whether a "subject" can access a "object" // with the operation "action", input parameters are usually: (sub, obj, act). -bool CachedEnforcer::Enforce(vector params) { +bool CachedEnforcer::Enforce(vector& params) { return EnforceWithMatcher("", params); } // Enforce with a map param,decides whether a "subject" can access a "object" // with the operation "action", input parameters are usually: (sub, obj, act). -bool CachedEnforcer::Enforce(unordered_map params) { +bool CachedEnforcer::Enforce(unordered_map& params) { return EnforceWithMatcher("", params); } diff --git a/casbin/enforcer_cached.h b/casbin/enforcer_cached.h index f019ad49..10a2141e 100644 --- a/casbin/enforcer_cached.h +++ b/casbin/enforcer_cached.h @@ -26,6 +26,10 @@ class CachedEnforcer : public Enforcer { unordered_map m; bool enableCache; mutex locker; + string model_path; + string policy_path; + shared_ptr adapter; + shared_ptr model; CachedEnforcer(const CachedEnforcer& ce); CachedEnforcer(CachedEnforcer&& ce); @@ -46,14 +50,14 @@ class CachedEnforcer : public Enforcer { * @param model_path the path of the model file. * @param policy_file the path of the policy file. */ - CachedEnforcer(string model_path, string policy_file); + CachedEnforcer(string& model_path, string& policy_file); /** * Enforcer initializes an enforcer with a database adapter. * * @param model_path the path of the model file. * @param adapter the adapter. */ - CachedEnforcer(string model_path, shared_ptr adapter); + CachedEnforcer(string& model_path, shared_ptr adapter); /** * Enforcer initializes an enforcer with a model and a database adapter. * @@ -66,13 +70,13 @@ class CachedEnforcer : public Enforcer { * * @param m the model. */ - CachedEnforcer(shared_ptr m); + explicit CachedEnforcer(shared_ptr m); /** * Enforcer initializes an enforcer with a model file. * * @param model_path the path of the model file. */ - CachedEnforcer(string model_path); + explicit CachedEnforcer(string& model_path); /** * Enforcer initializes an enforcer with a model file, a policy file and an enable log flag. * @@ -80,16 +84,16 @@ class CachedEnforcer : public Enforcer { * @param policy_file the path of the policy file. * @param enable_log whether to enable Casbin's log. */ - CachedEnforcer(string model_path, string policy_file, bool enable_log); + CachedEnforcer(string& model_path, string& policy_file, bool enable_log); bool Enforce(Scope scope); // Enforce with a vector param,decides whether a "subject" can access a // "object" with the operation "action", input parameters are usually: (sub, // obj, act). - bool Enforce(vector params); + bool Enforce(vector& params); // Enforce with a map param,decides whether a "subject" can access a "object" // with the operation "action", input parameters are usually: (sub, obj, act). - bool Enforce(unordered_map params); + bool Enforce(unordered_map& params); // EnforceWithMatcher use a custom matcher to decides whether a "subject" can // access a "object" with the operation "action", input parameters are // usually: (matcher, sub, obj, act), use model matcher by default when diff --git a/casbin/enforcer_interface.h b/casbin/enforcer_interface.h index 70dc7123..4535ffde 100644 --- a/casbin/enforcer_interface.h +++ b/casbin/enforcer_interface.h @@ -62,22 +62,22 @@ class IEnforcer { /* RBAC API */ virtual vector GetRolesForUser(string name, vector domain = {}) = 0; virtual vector GetUsersForRole(string name, vector domain = {}) = 0; - virtual bool HasRoleForUser(string name, string role) = 0; - virtual bool AddRoleForUser(string user, string role) = 0; - virtual bool AddRolesForUser(string user, vector roles) = 0; - virtual bool AddPermissionForUser(string user, vector permission) = 0; - virtual bool DeletePermissionForUser(string user, vector permission) = 0; - virtual bool DeletePermissionsForUser(string user) = 0; - virtual vector> GetPermissionsForUser(string user) = 0; - virtual bool HasPermissionForUser(string user, vector permission) = 0; + virtual bool HasRoleForUser(string name, string& role) = 0; + virtual bool AddRoleForUser(string& user, string& role) = 0; + virtual bool AddRolesForUser(string& user, vector roles) = 0; + virtual bool AddPermissionForUser(string& user, vector& permission) = 0; + virtual bool DeletePermissionForUser(string user, vector& permission) = 0; + virtual bool DeletePermissionsForUser(string& user) = 0; + virtual vector> GetPermissionsForUser(string& user) = 0; + virtual bool HasPermissionForUser(string& user, vector& permission) = 0; virtual vector GetImplicitRolesForUser(string name, vector domain = {}) = 0; virtual vector> GetImplicitPermissionsForUser(string user, vector domain = {}) = 0; virtual vector GetImplicitUsersForPermission(vector permission) = 0; - virtual bool DeleteRoleForUser(string user, string role) = 0; - virtual bool DeleteRolesForUser(string user) = 0; - virtual bool DeleteUser(string user) = 0; - virtual bool DeleteRole(string role) = 0; - virtual bool DeletePermission(vector permission) = 0; + virtual bool DeleteRoleForUser(string& user, string& role) = 0; + virtual bool DeleteRolesForUser(string& user) = 0; + virtual bool DeleteUser(string& user) = 0; + virtual bool DeleteRole(string& role) = 0; + virtual bool DeletePermission(vector& permission) = 0; /* Management API */ virtual vector GetAllSubjects() = 0; @@ -99,7 +99,7 @@ class IEnforcer { virtual bool HasPolicy(vector params) = 0; virtual bool HasNamedPolicy(string p_type, vector params) = 0; virtual bool AddPolicy(vector params) = 0; - virtual bool AddPolicies(vector> rules) = 0; + virtual bool AddPolicies(vector> rules) = 0; virtual bool AddNamedPolicy(string p_type, vector params) = 0; virtual bool AddNamedPolicies(string p_type, vector> rules) = 0; virtual bool RemovePolicy(vector params) = 0; @@ -130,11 +130,11 @@ class IEnforcer { virtual bool removeFilteredPolicy(string sec , string p_type , int field_index , vector field_values) = 0; /* RBAC API with domains.*/ - virtual vector GetUsersForRoleInDomain(string name, string domain) = 0; - virtual vector GetRolesForUserInDomain(string name, string domain) = 0; - virtual vector> GetPermissionsForUserInDomain(string user, string domain) = 0; - virtual bool AddRoleForUserInDomain(string user, string role, string domain) = 0; - virtual bool DeleteRoleForUserInDomain(string user, string role, string domain) = 0; + virtual vector GetUsersForRoleInDomain(string name, string& domain) = 0; + virtual vector GetRolesForUserInDomain(string name, string& domain) = 0; + virtual vector> GetPermissionsForUserInDomain(string& user, string& domain) = 0; + virtual bool AddRoleForUserInDomain(string& user, string& role, string& domain) = 0; + virtual bool DeleteRoleForUserInDomain(string& user, string& role, string& domain) = 0; }; #endif \ No newline at end of file diff --git a/casbin/error/error.h b/casbin/error/error.h index 0e415bc3..a889a0ec 100644 --- a/casbin/error/error.h +++ b/casbin/error/error.h @@ -10,11 +10,18 @@ class Error{ static Error NIL; string err; - Error(string error_message){ - err = error_message; + explicit Error(string& error_message):err(error_message) { } - string toString(){ + explicit Error(const char* error_message):err(error_message) { + + } + + explicit Error(const string& error_message):err(error_message) { + + } + + const string& toString() const{ return err; } }; diff --git a/casbin/exception/casbin_adapter_exception.cpp b/casbin/exception/casbin_adapter_exception.cpp index 71c10432..7d60ecdd 100644 --- a/casbin/exception/casbin_adapter_exception.cpp +++ b/casbin/exception/casbin_adapter_exception.cpp @@ -6,8 +6,11 @@ #include "./casbin_adapter_exception.h" -CasbinAdapterException :: CasbinAdapterException(string error_message) { - this->error_message = error_message; +CasbinAdapterException :: CasbinAdapterException(string& error_message): error_message(error_message) { +} + +CasbinAdapterException ::CasbinAdapterException(const char *error_message): error_message(error_message) { + } #endif // CASBIN_ADAPTER_EXCEPTION_CPP diff --git a/casbin/exception/casbin_adapter_exception.h b/casbin/exception/casbin_adapter_exception.h index a8ff991e..7ab95b87 100644 --- a/casbin/exception/casbin_adapter_exception.h +++ b/casbin/exception/casbin_adapter_exception.h @@ -9,7 +9,8 @@ using namespace std; class CasbinAdapterException{ string error_message; public: - CasbinAdapterException(string error_message); + explicit CasbinAdapterException(string& error_message); + explicit CasbinAdapterException(const char* error_message); }; #endif \ No newline at end of file diff --git a/casbin/exception/casbin_enforcer_exception.cpp b/casbin/exception/casbin_enforcer_exception.cpp index d9b38d57..d7c94083 100644 --- a/casbin/exception/casbin_enforcer_exception.cpp +++ b/casbin/exception/casbin_enforcer_exception.cpp @@ -6,8 +6,11 @@ #include "./casbin_enforcer_exception.h" -CasbinEnforcerException :: CasbinEnforcerException(string error_message){ - this->error_message = error_message; +CasbinEnforcerException :: CasbinEnforcerException(string& error_message):error_message(error_message) { +} + +CasbinEnforcerException ::CasbinEnforcerException(const char *error_message):error_message(error_message) { + } #endif // CASBIN_ENFORCER_EXCEPTION_CPP diff --git a/casbin/exception/casbin_enforcer_exception.h b/casbin/exception/casbin_enforcer_exception.h index 6c8b808a..36d8cc61 100644 --- a/casbin/exception/casbin_enforcer_exception.h +++ b/casbin/exception/casbin_enforcer_exception.h @@ -9,7 +9,8 @@ using namespace std; class CasbinEnforcerException{ string error_message; public: - CasbinEnforcerException(string error_message); + explicit CasbinEnforcerException(string& error_message); + explicit CasbinEnforcerException(const char* error_message); }; #endif \ No newline at end of file diff --git a/casbin/exception/casbin_rbac_exception.cpp b/casbin/exception/casbin_rbac_exception.cpp index 3f048709..b8a00ee4 100644 --- a/casbin/exception/casbin_rbac_exception.cpp +++ b/casbin/exception/casbin_rbac_exception.cpp @@ -6,8 +6,11 @@ #include "./casbin_rbac_exception.h" -CasbinRBACException :: CasbinRBACException(string error_message){ - this->error_message = error_message; +CasbinRBACException :: CasbinRBACException(string& error_message):error_message(error_message) { +} + +CasbinRBACException ::CasbinRBACException(const char *error_message):error_message(error_message) { + } #endif // CASBIN_RBAC_EXCEPTION_CPP diff --git a/casbin/exception/casbin_rbac_exception.h b/casbin/exception/casbin_rbac_exception.h index 0f468065..ccc8c403 100644 --- a/casbin/exception/casbin_rbac_exception.h +++ b/casbin/exception/casbin_rbac_exception.h @@ -9,7 +9,8 @@ using namespace std; class CasbinRBACException{ string error_message; public: - CasbinRBACException(string error_message); + explicit CasbinRBACException(string& error_message); + explicit CasbinRBACException(const char* error_message); }; #endif \ No newline at end of file diff --git a/casbin/exception/illegal_argument_exception.cpp b/casbin/exception/illegal_argument_exception.cpp index cf7a9a7f..d25d5436 100644 --- a/casbin/exception/illegal_argument_exception.cpp +++ b/casbin/exception/illegal_argument_exception.cpp @@ -5,9 +5,15 @@ #include "./illegal_argument_exception.h" +IllegalArgumentException :: IllegalArgumentException(string& error_message):error_message(error_message) { +} + +IllegalArgumentException :: IllegalArgumentException(const char *error_message):error_message(error_message) { + +} + +IllegalArgumentException :: IllegalArgumentException(const string &error_message):error_message(error_message) { -IllegalArgumentException :: IllegalArgumentException(string error_message) { - this->error_message = error_message; } #endif // ILLEGAL_ARGUMENT_EXCEPTION_CPP diff --git a/casbin/exception/illegal_argument_exception.h b/casbin/exception/illegal_argument_exception.h index f44c533c..f231e85d 100644 --- a/casbin/exception/illegal_argument_exception.h +++ b/casbin/exception/illegal_argument_exception.h @@ -9,7 +9,11 @@ using namespace std; class IllegalArgumentException{ string error_message; public: - IllegalArgumentException(string error_message); + //explicit IllegalArgumentException(string error_message); + explicit IllegalArgumentException(string& error_message); + explicit IllegalArgumentException(const char* error_message); + explicit IllegalArgumentException(const string& error_message); + }; #endif \ No newline at end of file diff --git a/casbin/exception/io_exception.cpp b/casbin/exception/io_exception.cpp index 24881e5f..57e359c2 100644 --- a/casbin/exception/io_exception.cpp +++ b/casbin/exception/io_exception.cpp @@ -6,8 +6,11 @@ #include "./io_exception.h" -IOException :: IOException(string error_message) { - this->error_message = error_message; +IOException :: IOException(string& error_message):error_message(error_message) { +} + +IOException ::IOException(const char *erro_message):error_message(erro_message) { + } #endif //IO_EXCEPTION diff --git a/casbin/exception/io_exception.h b/casbin/exception/io_exception.h index e40bf8c3..018f8171 100644 --- a/casbin/exception/io_exception.h +++ b/casbin/exception/io_exception.h @@ -9,7 +9,8 @@ using namespace std; class IOException{ string error_message; public: - IOException(string error_message); + explicit IOException(string& error_message); + explicit IOException(const char* erro_message); }; #endif \ No newline at end of file diff --git a/casbin/exception/missing_required_sections.cpp b/casbin/exception/missing_required_sections.cpp index 4461fe7a..1bbd5dba 100644 --- a/casbin/exception/missing_required_sections.cpp +++ b/casbin/exception/missing_required_sections.cpp @@ -6,8 +6,15 @@ #include "./missing_required_sections.h" -MissingRequiredSections :: MissingRequiredSections(string error_message) { - this->error_message = error_message; +MissingRequiredSections :: MissingRequiredSections(string& error_message):error_message(error_message) { +} + +MissingRequiredSections :: MissingRequiredSections(const char *error_message):error_message(error_message) { + +} + +MissingRequiredSections :: MissingRequiredSections(const string& error_message):error_message(error_message) { + } #endif // MISSING_REQUIRED_SECTIONS_CPP diff --git a/casbin/exception/missing_required_sections.h b/casbin/exception/missing_required_sections.h index d9c8f451..e54a0bf2 100644 --- a/casbin/exception/missing_required_sections.h +++ b/casbin/exception/missing_required_sections.h @@ -9,7 +9,9 @@ using namespace std; class MissingRequiredSections{ string error_message; public: - MissingRequiredSections(string error_message); + explicit MissingRequiredSections(string& error_message); + explicit MissingRequiredSections(const char* error_message); + explicit MissingRequiredSections(const string& erro_message); }; #endif \ No newline at end of file diff --git a/casbin/exception/unsupported_operation_exception.cpp b/casbin/exception/unsupported_operation_exception.cpp index dfd7cf4d..df4647da 100644 --- a/casbin/exception/unsupported_operation_exception.cpp +++ b/casbin/exception/unsupported_operation_exception.cpp @@ -6,8 +6,11 @@ #include "./unsupported_operation_exception.h" -UnsupportedOperationException :: UnsupportedOperationException(string error_message) { - this->error_message = error_message; +UnsupportedOperationException :: UnsupportedOperationException(string& error_message):error_message(error_message) { +} + +UnsupportedOperationException ::UnsupportedOperationException(const char *error_message):error_message(error_message) { + } #endif // UNSUPPORTED_OPERATION_EXCEPTION_CPP diff --git a/casbin/exception/unsupported_operation_exception.h b/casbin/exception/unsupported_operation_exception.h index 6f161f41..b2ec2301 100644 --- a/casbin/exception/unsupported_operation_exception.h +++ b/casbin/exception/unsupported_operation_exception.h @@ -9,7 +9,8 @@ using namespace std; class UnsupportedOperationException{ string error_message; public: - UnsupportedOperationException(string error_message); + explicit UnsupportedOperationException(string& error_message); + explicit UnsupportedOperationException(const char* error_message); }; #endif \ No newline at end of file diff --git a/casbin/internal_api.cpp b/casbin/internal_api.cpp index 28dae6d7..3f101bf0 100644 --- a/casbin/internal_api.cpp +++ b/casbin/internal_api.cpp @@ -41,7 +41,7 @@ bool Enforcer :: addPolicy(string sec, string p_type, vector rule) { try { this->adapter->AddPolicy(sec, p_type, rule); } - catch(UnsupportedOperationException e) { + catch(UnsupportedOperationException& e) { } } @@ -70,7 +70,7 @@ bool Enforcer :: addPolicies(string sec, string p_type, vector> r try { dynamic_pointer_cast(this->adapter)->AddPolicies(sec, p_type, rules); } - catch(UnsupportedOperationException e) { + catch(UnsupportedOperationException& e) { } } @@ -95,7 +95,7 @@ bool Enforcer :: removePolicy(string sec, string p_type, vector rule) { try { this->adapter->RemovePolicy(sec, p_type, rule); } - catch (UnsupportedOperationException e) { + catch (UnsupportedOperationException& e) { } } @@ -123,7 +123,7 @@ bool Enforcer :: removePolicies(string sec, string p_type, vector try{ dynamic_pointer_cast(this->adapter)->RemovePolicies(sec, p_type, rules); } - catch(UnsupportedOperationException e){ + catch(UnsupportedOperationException& e){ } } @@ -149,7 +149,7 @@ bool Enforcer :: removeFilteredPolicy(string sec, string p_type, int field_index try { this->adapter->RemoveFilteredPolicy(sec, p_type, field_index, field_values); \ } - catch (UnsupportedOperationException e) { + catch (UnsupportedOperationException& e) { } } diff --git a/casbin/ip_parser/exception/parser_exception.cpp b/casbin/ip_parser/exception/parser_exception.cpp index 041af8d4..9aacc7fd 100644 --- a/casbin/ip_parser/exception/parser_exception.cpp +++ b/casbin/ip_parser/exception/parser_exception.cpp @@ -6,8 +6,15 @@ #include "./parser_exception.h" -ParserException :: ParserException(string error_message){ - this->error_message = error_message; +ParserException :: ParserException(string& error_message):error_message(error_message) { +} + +ParserException ::ParserException(const char *error_message):error_message(error_message) { + +} + +ParserException ::ParserException(const string &error_message):error_message(error_message) { + } #endif // PARSER_EXCEPTION_CPP diff --git a/casbin/ip_parser/exception/parser_exception.h b/casbin/ip_parser/exception/parser_exception.h index 9eb052fe..ae054038 100644 --- a/casbin/ip_parser/exception/parser_exception.h +++ b/casbin/ip_parser/exception/parser_exception.h @@ -8,7 +8,9 @@ using namespace std; class ParserException{ string error_message; public: - ParserException(string error_message); + explicit ParserException(string& error_message); + explicit ParserException(const char* error_message); + explicit ParserException(const string& error_message); }; #endif \ No newline at end of file diff --git a/casbin/ip_parser/parser/IP.cpp b/casbin/ip_parser/parser/IP.cpp index 5bd18a80..76ebabf3 100644 --- a/casbin/ip_parser/parser/IP.cpp +++ b/casbin/ip_parser/parser/IP.cpp @@ -1,3 +1,11 @@ +/* + * @Author: your name + * @Date: 2021-03-23 07:30:29 + * @LastEditTime: 2021-03-23 13:42:18 + * @LastEditors: your name + * @Description: In User Settings Edit + * @FilePath: /casbin/casbin/ip_parser/parser/IP.cpp + */ #include "pch.h" #ifndef IP_CPP @@ -6,8 +14,8 @@ #include "./IP.h" -byte IP :: IPv4len = 4; -byte IP :: IPv6len = 16; +Byte IP :: IPv4len = 4; +Byte IP :: IPv6len = 16; IPMask IP :: v4InV6Prefix{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; IP :: IP() { @@ -29,17 +37,17 @@ IP IP :: Mask(IPMask mask) { ip = ip_3; } } - unsigned int n = int(ip.size()); + unsigned int n = static_cast(ip.size()); if(n != mask.size()) { IP ip_mask; ip_mask.isLegal = false; return ip_mask; } IP out; - vector outNew(n, 0); + vector outNew(n, 0); out.ip = outNew; out.isLegal = true; - for(int i = 0; i < int(n); i++) { + for(int i = 0; i < static_cast(n); i++) { out.ip[i] = ip[i] & mask[i]; } return out; @@ -50,13 +58,13 @@ bool IP :: Equal(IP x) { return equal(ip, x.ip); } if(ip.size() == IPv4len && x.ip.size() == IPv6len) { - vector xNew1(x.ip.begin(), x.ip.begin() + 12); - vector xNew2(x.ip.begin() + 12, x.ip.end()); + vector xNew1(x.ip.begin(), x.ip.begin() + 12); + vector xNew2(x.ip.begin() + 12, x.ip.end()); return equal(xNew1, v4InV6Prefix) && equal(ip, xNew2); } if(ip.size() == IPv6len && x.ip.size() == IPv4len) { - vector ipNew1(ip.begin(), ip.begin() + 12); - vector ipNew2(ip.begin() + 12, ip.end()); + vector ipNew1(ip.begin(), ip.begin() + 12); + vector ipNew2(ip.begin() + 12, ip.end()); return equal(ipNew1, v4InV6Prefix) && equal(ipNew2, x.ip); } return false; @@ -83,11 +91,11 @@ IP IP :: To4() { return *this; } IP ipNew; - vector ipN (ip.begin(), ip.begin() + 10); + vector ipN (ip.begin(), ip.begin() + 10); ipNew.ip = ipN; if(ip.size() == IPv6len && isZeros(ipNew) && ip[10] == 0xff && ip[11] == 0xff) { IP ipNew2; - vector ipN(ip.begin() + 12, ip.begin() + 16); + vector ipN(ip.begin() + 12, ip.begin() + 16); ipNew2.ip = ipN; return ipNew2; } @@ -97,7 +105,7 @@ IP IP :: To4() { // Is p all zeros? bool IP :: isZeros(IP p) { - for(int i = 0 ; i < p.ip.size() ; i++ ) { + for(auto i = 0 ; i < p.ip.size() ; i++ ) { if(p.ip[i] != 0) { return false; } diff --git a/casbin/ip_parser/parser/IP.h b/casbin/ip_parser/parser/IP.h index 47488e34..c174773a 100644 --- a/casbin/ip_parser/parser/IP.h +++ b/casbin/ip_parser/parser/IP.h @@ -1,3 +1,11 @@ +/* + * @Author: your name + * @Date: 2021-03-23 07:30:29 + * @LastEditTime: 2021-03-23 13:37:19 + * @LastEditors: Please set LastEditors + * @Description: In User Settings Edit + * @FilePath: /casbin/casbin/ip_parser/parser/IP.h + */ #ifndef IP_PARSER_PARSER_IP #define IP_PARSER_PARSER_IP @@ -13,10 +21,10 @@ using namespace std; class IP { public: - vector ip; + vector ip; bool isLegal; - static byte IPv4len; - static byte IPv6len; + static Byte IPv4len; + static Byte IPv6len; static IPMask v4InV6Prefix; IP(); diff --git a/casbin/ip_parser/parser/IPMask.h b/casbin/ip_parser/parser/IPMask.h index 7de47868..b812f56e 100644 --- a/casbin/ip_parser/parser/IPMask.h +++ b/casbin/ip_parser/parser/IPMask.h @@ -7,6 +7,6 @@ using namespace std; -typedef vector < byte > IPMask; +typedef vector < Byte > IPMask; #endif \ No newline at end of file diff --git a/casbin/ip_parser/parser/IPNet.cpp b/casbin/ip_parser/parser/IPNet.cpp index 3e88858d..800a6950 100644 --- a/casbin/ip_parser/parser/IPNet.cpp +++ b/casbin/ip_parser/parser/IPNet.cpp @@ -68,8 +68,8 @@ pair IPNet :: networkNumberAndMask(IPNet n) { } IPMask m = n.mask; p.second = m; - const byte ipv4len = IP :: IPv4len; - const byte ipv6len = IP :: IPv6len; + const Byte ipv4len = IP :: IPv4len; + const Byte ipv6len = IP :: IPv6len; if(m.size() == ipv4len){ if(newIp.ip.size() != IP :: IPv4len) { p.first.isLegal = false; diff --git a/casbin/ip_parser/parser/IPv4.cpp b/casbin/ip_parser/parser/IPv4.cpp index cd926e32..b4cc0751 100644 --- a/casbin/ip_parser/parser/IPv4.cpp +++ b/casbin/ip_parser/parser/IPv4.cpp @@ -6,9 +6,9 @@ #include "./IPv4.h" -IP IPv4(byte a, byte b, byte c, byte d) { +IP IPv4(Byte a, Byte b, Byte c, Byte d) { IP p; - vector newIP(IP :: v4InV6Prefix.begin(), IP :: v4InV6Prefix.end()); + vector newIP(IP :: v4InV6Prefix.begin(), IP :: v4InV6Prefix.end()); p.ip = newIP; p.ip.push_back(a); p.ip.push_back(b); diff --git a/casbin/ip_parser/parser/IPv4.h b/casbin/ip_parser/parser/IPv4.h index 2aee64d8..74dfd484 100644 --- a/casbin/ip_parser/parser/IPv4.h +++ b/casbin/ip_parser/parser/IPv4.h @@ -4,6 +4,6 @@ #include "./IP.h" #include "./byte.h" -IP IPv4(byte a, byte b, byte c, byte d); +IP IPv4(Byte a, Byte b, Byte c, Byte d); #endif \ No newline at end of file diff --git a/casbin/ip_parser/parser/Print.cpp b/casbin/ip_parser/parser/Print.cpp index f07dd969..d685c9d8 100644 --- a/casbin/ip_parser/parser/Print.cpp +++ b/casbin/ip_parser/parser/Print.cpp @@ -7,7 +7,7 @@ #include "./Print.h" void Print(IP ip_addr) { - for(int i = 0 ; i < ip_addr.ip.size() ; i++){ + for(auto i = 0 ; i < ip_addr.ip.size() ; i++){ cout< b) { - for(int i = 0 ; i < b.size() ; i++){ +bool allFF(vector b) { + for(auto i = 0 ; i < b.size() ; i++){ if(b[i] != 0xff) { return false; } diff --git a/casbin/ip_parser/parser/allFF.h b/casbin/ip_parser/parser/allFF.h index 88b0fd36..b54d6b5f 100644 --- a/casbin/ip_parser/parser/allFF.h +++ b/casbin/ip_parser/parser/allFF.h @@ -7,6 +7,6 @@ using namespace std; -bool allFF(vector b); +bool allFF(vector b); #endif \ No newline at end of file diff --git a/casbin/ip_parser/parser/byte.h b/casbin/ip_parser/parser/byte.h index 7685c50c..8f544f72 100644 --- a/casbin/ip_parser/parser/byte.h +++ b/casbin/ip_parser/parser/byte.h @@ -1,7 +1,8 @@ #ifndef IP_PARSER_PARSER_BYTE #define IP_PARSER_PARSER_BYTE -typedef unsigned short int byte; +using namespace std; +typedef unsigned short int Byte; const unsigned int big = 0xFFFFFF; diff --git a/casbin/ip_parser/parser/parseCIDR.cpp b/casbin/ip_parser/parser/parseCIDR.cpp index 6a1854ce..2aec13f9 100644 --- a/casbin/ip_parser/parser/parseCIDR.cpp +++ b/casbin/ip_parser/parser/parseCIDR.cpp @@ -13,7 +13,7 @@ CIDR parseCIDR(string s) { } string addr = s.substr(0, pos); string mask = s.substr(pos+1, s.length()-pos-1); - byte iplen = IP :: IPv4len; + Byte iplen = IP :: IPv4len; IP ip; ip = parseIPv4(addr); if(ip.isLegal == false) { diff --git a/casbin/ip_parser/parser/parseIPv4.cpp b/casbin/ip_parser/parser/parseIPv4.cpp index 61729dab..b7f3a710 100644 --- a/casbin/ip_parser/parser/parseIPv4.cpp +++ b/casbin/ip_parser/parser/parseIPv4.cpp @@ -7,7 +7,7 @@ #include "./parseIPv4.h" IP parseIPv4(string s) { - vector pb(IP :: IPv4len, 0); + vector pb(IP :: IPv4len, 0); IP ipv4; for(int i = 0; i < IP :: IPv4len ; i++) { if(s.length() == 0) { diff --git a/casbin/ip_parser/parser/parseIPv6.cpp b/casbin/ip_parser/parser/parseIPv6.cpp index 6e26e281..492bf016 100644 --- a/casbin/ip_parser/parser/parseIPv6.cpp +++ b/casbin/ip_parser/parser/parseIPv6.cpp @@ -8,7 +8,7 @@ IP parseIPv6(string s) { IP ipv6; - vector newIP(IP :: IPv6len, 0); + vector newIP(IP :: IPv6len, 0); ipv6.ip = newIP; int ellipsis = -1; // position of ellipsis in ip @@ -58,8 +58,8 @@ IP parseIPv6(string s) { } // Save this 16-bit chunk. - ipv6.ip[i] = byte(p.first >> 8); - ipv6.ip[i+1] = byte(p.first); + ipv6.ip[i] = Byte(p.first >> 8); + ipv6.ip[i+1] = Byte(p.first); i += 2; // Stop at end of string. diff --git a/casbin/model/assertion.cpp b/casbin/model/assertion.cpp index 6da66f64..38aaf781 100644 --- a/casbin/model/assertion.cpp +++ b/casbin/model/assertion.cpp @@ -27,12 +27,12 @@ void Assertion :: BuildIncrementalRoleLinks(shared_ptr rm, policy_op op, vector> rules) { this->rm = rm; - int char_count = int(count(this->value.begin(), this->value.end(), '_')); + int char_count = static_cast(count(this->value.begin(), this->value.end(), '_')); if (char_count < 2) throw IllegalArgumentException("the number of \"_\" in role definition should be at least 2"); - for(int i = 0 ; i < rules.size() ; i++){ + for(auto i = 0 ; i < rules.size() ; i++){ vector rule = rules[i]; if (rule.size() < char_count) @@ -54,7 +54,7 @@ void Assertion :: BuildIncrementalRoleLinks(shared_ptr rm, policy_o void Assertion :: BuildRoleLinks(shared_ptr rm) { this->rm = rm; - int char_count = int(count(this->value.begin(), this->value.end(), '_')); + int char_count = static_cast(count(this->value.begin(), this->value.end(), '_')); if (char_count < 2) throw IllegalArgumentException("the number of \"_\" in role definition should be at least 2"); diff --git a/casbin/model/function.cpp b/casbin/model/function.cpp index 8eea4e69..fdab488c 100644 --- a/casbin/model/function.cpp +++ b/casbin/model/function.cpp @@ -24,28 +24,28 @@ #include "../util/util.h" FunctionMap :: FunctionMap(){ - scope = NULL; + scope = nullptr; } void FunctionMap :: ProcessFunctions(string expression){ for(auto func: func_list){ - int index = int(expression.find(func+"(")); + auto index = expression.find(func+"("); if(index != string::npos){ - int close_index = int(expression.find(")", index)); - int start = index + int((func+"(").length()); + auto close_index = expression.find(")", index); + auto start = index + (func+"(").length(); string function_params = expression.substr(start, close_index-start); FetchIdentifier(this->scope, func); vector params = Split(function_params, ","); - for(int i=0;iscope, Trim(params[i])); else{ params[i] = params[i].replace(quote_index, 1, "'"); - int second_quote_index = int(params[i].find("\"", quote_index+1)); + auto second_quote_index = params[i].find("\"", quote_index+1); params[i] = params[i].replace(second_quote_index, 1, "'"); Get(this->scope, Trim(params[i])); } @@ -61,7 +61,7 @@ int FunctionMap :: GetRLen(){ return -1; } -bool FunctionMap :: Evaluate(string expression){ +bool FunctionMap :: Evaluate(string& expression){ ProcessFunctions(expression); return Eval(scope, expression); } @@ -71,48 +71,48 @@ bool FunctionMap :: GetBooleanResult(){ } // AddFunction adds an expression function. -void FunctionMap :: AddFunction(string func_name, Function f, Index nargs) { +void FunctionMap :: AddFunction(const string& func_name, Function f, Index nargs) { func_list.push_back(func_name); PushFunction(scope, f, func_name, nargs); } -void FunctionMap :: AddFunctionPropToR(string identifier, Function func, Index nargs){ +void FunctionMap :: AddFunctionPropToR(string& identifier, Function func, Index nargs){ PushFunctionPropToObject(scope, "r", func, identifier, nargs); } -void FunctionMap :: AddBooleanPropToR(string identifier, bool val){ +void FunctionMap :: AddBooleanPropToR(string& identifier, bool val){ PushBooleanPropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddTruePropToR(string identifier){ +void FunctionMap :: AddTruePropToR(string& identifier){ PushTruePropToObject(scope, "r", identifier); } -void FunctionMap :: AddFalsePropToR(string identifier){ +void FunctionMap :: AddFalsePropToR(string& identifier){ PushFalsePropToObject(scope, "r", identifier); } -void FunctionMap :: AddIntPropToR(string identifier, int val){ +void FunctionMap :: AddIntPropToR(string& identifier, int val){ PushIntPropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddFloatPropToR(string identifier, float val){ +void FunctionMap :: AddFloatPropToR(string& identifier, float val){ PushFloatPropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddDoublePropToR(string identifier, double val){ +void FunctionMap :: AddDoublePropToR(string& identifier, double val){ PushDoublePropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddStringPropToR(string identifier, string val){ +void FunctionMap :: AddStringPropToR(string& identifier, string& val){ PushStringPropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddPointerPropToR(string identifier, void* val){ +void FunctionMap :: AddPointerPropToR(string& identifier, void* val){ PushPointerPropToObject(scope, "r", val, identifier); } -void FunctionMap :: AddObjectPropToR(string identifier){ +void FunctionMap :: AddObjectPropToR(string& identifier){ PushObjectPropToObject(scope, "r", identifier); } diff --git a/casbin/model/function.h b/casbin/model/function.h index 09ff254b..3143b3ae 100644 --- a/casbin/model/function.h +++ b/casbin/model/function.h @@ -34,32 +34,32 @@ class FunctionMap { int GetRLen(); - bool Evaluate(string expression); + bool Evaluate(string& expression); bool GetBooleanResult(); // AddFunction adds an expression function. - void AddFunction(string func_name, Function f, Index nargs); + void AddFunction(const string& func_name, Function f, Index nargs); - void AddFunctionPropToR(string identifier, Function func, Index nargs); + void AddFunctionPropToR(string& identifier, Function func, Index nargs); - void AddBooleanPropToR(string identifier, bool val); + void AddBooleanPropToR(string& identifier, bool val); - void AddTruePropToR(string identifier); + void AddTruePropToR(string& identifier); - void AddFalsePropToR(string identifier); + void AddFalsePropToR(string& identifier); - void AddIntPropToR(string identifier, int val); + void AddIntPropToR(string& identifier, int val); - void AddFloatPropToR(string identifier, float val); + void AddFloatPropToR(string& identifier, float val); - void AddDoublePropToR(string identifier, double val); + void AddDoublePropToR(string& identifier, double val); - void AddStringPropToR(string identifier, string val); + void AddStringPropToR(string& identifier, string& val); - void AddPointerPropToR(string identifier, void* val); + void AddPointerPropToR(string& identifier, void* val); - void AddObjectPropToR(string identifier); + void AddObjectPropToR(string& identifier); // LoadFunctionMap loads an initial function map. void LoadFunctionMap(); diff --git a/casbin/model/model.cpp b/casbin/model/model.cpp index ff386dbd..6dabd522 100644 --- a/casbin/model/model.cpp +++ b/casbin/model/model.cpp @@ -40,11 +40,11 @@ unordered_map Model :: section_name_map = { vector Model :: required_sections{"r","p","e","m"}; void Model :: LoadModelFromConfig(shared_ptr cfg) { - for(unordered_map :: iterator it = section_name_map.begin() ; it != section_name_map.end() ; it++) + for(unordered_map :: iterator it = section_name_map.begin() ; it != section_name_map.end() ; ++it) LoadSection(this, cfg, it->first); vector ms; - for(int i=0 ; i < required_sections.size() ; i++) + for(auto i=0 ; i < required_sections.size() ; i++) if(!this->HasSection(required_sections[i])) ms.push_back(section_name_map[required_sections[i]]); @@ -52,11 +52,11 @@ void Model :: LoadModelFromConfig(shared_ptr cfg) { throw MissingRequiredSections("missing required sections: " + Join(ms, ",")); } -bool Model :: HasSection(string sec) { +bool Model :: HasSection(string& sec) { return this->m.find(sec) != this->m.end(); } -void Model :: LoadSection(Model* model, shared_ptr cfg, string sec) { +void Model :: LoadSection(Model* model, shared_ptr cfg,const string& sec) { int i = 1; while(true) { if (!LoadAssertion(model, cfg, sec, sec+GetKeySuffix(i))){ @@ -77,13 +77,13 @@ string Model :: GetKeySuffix(int i) { return s; } -bool Model :: LoadAssertion(Model* model, shared_ptr cfg, string sec, string key) { +bool Model :: LoadAssertion(Model* model, shared_ptr cfg,const string& sec,const string& key) { string value = cfg->GetString(section_name_map[sec] + "::" + key); return model->AddDef(sec, key, value); } // AddDef adds an assertion to the model. -bool Model :: AddDef(string sec, string key, string value) { +bool Model :: AddDef(const string& sec,const string& key, string& value) { if(value == "") return false; @@ -108,13 +108,13 @@ bool Model :: AddDef(string sec, string key, string value) { } // LoadModel loads the model from model CONF file. -void Model :: LoadModel(string path) { +void Model :: LoadModel(string& path) { shared_ptr cfg = Config::NewConfig(path); LoadModelFromConfig(cfg); } // LoadModelFromText loads the model from the text. -void Model :: LoadModelFromText(string text) { +void Model :: LoadModelFromText(string& text) { shared_ptr cfg = Config::NewConfigFromText(text); LoadModelFromConfig(cfg); } @@ -138,7 +138,7 @@ void Model :: PrintModel() { Model :: Model(){ } -Model :: Model(string path){ +Model :: Model(string& path){ LoadModel(path); } @@ -148,27 +148,27 @@ Model* Model :: NewModel() { } // NewModel creates a model from a .CONF file. -Model* Model :: NewModelFromFile(string path) { +Model* Model :: NewModelFromFile(string& path) { Model* m = NewModel(); m->LoadModel(path); return m; } // NewModel creates a model from a string which contains model text. -Model* Model :: NewModelFromString(string text) { +Model* Model :: NewModelFromString(string& text) { Model* m = NewModel(); m->LoadModelFromText(text); return m; } -void Model :: BuildIncrementalRoleLinks(shared_ptr rm, policy_op op, string sec, string p_type, vector> rules) { +void Model :: BuildIncrementalRoleLinks(shared_ptr rm, policy_op op,const string& sec, string& p_type, vector> rules) { if (sec == "g") this->m[sec].assertion_map[p_type]->BuildIncrementalRoleLinks(rm, op, rules); } // BuildRoleLinks initializes the roles in RBAC. void Model :: BuildRoleLinks(shared_ptr rm) { - for (unordered_map> :: iterator it = this->m["g"].assertion_map.begin() ; it != this->m["g"].assertion_map.end() ; it++) + for (unordered_map> :: iterator it = this->m["g"].assertion_map.begin() ; it != this->m["g"].assertion_map.end() ; ++it) (it->second)->BuildRoleLinks(rm); } @@ -193,29 +193,29 @@ void Model :: PrintPolicy() { // ClearPolicy clears all current policy. void Model :: ClearPolicy() { - for (unordered_map> :: iterator it = this->m["p"].assertion_map.begin() ; it != this->m["p"].assertion_map.end() ; it++){ + for (unordered_map> :: iterator it = this->m["p"].assertion_map.begin() ; it != this->m["p"].assertion_map.end() ; ++it){ if((it->second)->policy.size() > 0) (it->second)->policy.clear(); } - for (unordered_map> :: iterator it = this->m["g"].assertion_map.begin() ; it != this->m["g"].assertion_map.end() ; it++){ + for (unordered_map> :: iterator it = this->m["g"].assertion_map.begin() ; it != this->m["g"].assertion_map.end() ; ++it){ if((it->second)->policy.size() > 0) (it->second)->policy.clear(); } } // GetPolicy gets all rules in a policy. -vector> Model :: GetPolicy(string sec, string p_type) { +vector> Model :: GetPolicy(const string& sec, string& p_type) { return (this->m)[sec].assertion_map[p_type]->policy; } // GetFilteredPolicy gets rules based on field filters from a policy. -vector> Model :: GetFilteredPolicy(string sec, string p_type, int field_index, vector field_values) { +vector> Model :: GetFilteredPolicy(const string& sec, string& p_type, int field_index, vector field_values) { vector> res; vector> policy(m[sec].assertion_map[p_type]->policy); - for(int i = 0 ; i < policy.size() ; i++){ + for(size_t i = 0 ; i < policy.size() ; i++){ bool matched = true; - for(int j = 0 ; j < field_values.size() ; j++){ + for(size_t j = 0 ; j < field_values.size() ; j++){ if(field_values[j] != "" && (policy[i])[field_index + j] != field_values[j] ){ matched = false; break; @@ -229,9 +229,9 @@ vector> Model :: GetFilteredPolicy(string sec, string p_type, int } // HasPolicy determines whether a model has the specified policy rule. -bool Model :: HasPolicy(string sec, string p_type, vector rule) { +bool Model :: HasPolicy(const string& sec, string& p_type, vector& rule) { vector> policy = m[sec].assertion_map[p_type]->policy; - for(int i=0 ; i < policy.size() ; i++) + for(size_t i=0 ; i < policy.size() ; i++) if (ArrayEquals(rule, policy[i])) return true; @@ -239,7 +239,7 @@ bool Model :: HasPolicy(string sec, string p_type, vector rule) { } // AddPolicy adds a policy rule to the model. -bool Model :: AddPolicy(string sec, string p_type, vector rule) { +bool Model :: AddPolicy(string& sec, string& p_type, vector& rule) { if(!this->HasPolicy(sec, p_type, rule)) { m[sec].assertion_map[p_type]->policy.push_back(rule); return true; @@ -249,20 +249,20 @@ bool Model :: AddPolicy(string sec, string p_type, vector rule) { } // AddPolicies adds policy rules to the model. -bool Model :: AddPolicies(string sec, string p_type, vector> rules) { - for (int i = 0; i < rules.size(); i++) +bool Model :: AddPolicies(string& sec, string& p_type, vector> rules) { + for (size_t i = 0; i < rules.size(); i++) if (this->HasPolicy(sec, p_type, rules[i])) return false; - for (int i = 0; i < rules.size(); i++) + for (size_t i = 0; i < rules.size(); i++) this->m[sec].assertion_map[p_type]->policy.push_back(rules[i]); return true; } // RemovePolicy removes a policy rule from the model. -bool Model :: RemovePolicy(string sec, string p_type, vector rule) { - for (int i = 0 ; i < m[sec].assertion_map[p_type]->policy.size() ; i++) { +bool Model :: RemovePolicy(string& sec, string& p_type, vector& rule) { + for (size_t i = 0 ; i < m[sec].assertion_map[p_type]->policy.size() ; i++) { if (ArrayEquals(rule, m[sec].assertion_map[p_type]->policy[i])) { m[sec].assertion_map[p_type]->policy.erase(m[sec].assertion_map[p_type]->policy.begin() + i); return true; @@ -273,17 +273,17 @@ bool Model :: RemovePolicy(string sec, string p_type, vector rule) { } // RemovePolicies removes policy rules from the model. -bool Model :: RemovePolicies(string sec, string p_type, vector> rules) { - OUTER: for (int j = 0; j < rules.size(); j++) { - for (int i = 0; i < this->m[sec].assertion_map[p_type]->policy.size(); i++){ +bool Model :: RemovePolicies(string& sec, string& p_type, vector> rules) { + OUTER: for (auto j = 0; j < rules.size(); j++) { + for (auto i = 0; i < this->m[sec].assertion_map[p_type]->policy.size(); i++){ if (ArrayEquals(rules[j], this->m[sec].assertion_map[p_type]->policy[i])) goto OUTER; } return false; } - for (int j = 0; j < rules.size(); j++){ - for (int i = 0; i < this->m[sec].assertion_map[p_type]->policy.size(); i++){ + for (size_t j = 0; j < rules.size(); j++){ + for (size_t i = 0; i < this->m[sec].assertion_map[p_type]->policy.size(); i++){ if (ArrayEquals(rules[j], this->m[sec].assertion_map[p_type]->policy[i])) this->m[sec].assertion_map[p_type]->policy.erase(this->m[sec].assertion_map[p_type]->policy.begin() + i); } @@ -293,14 +293,14 @@ bool Model :: RemovePolicies(string sec, string p_type, vector> r } // RemoveFilteredPolicy removes policy rules based on field filters from the model. -pair>> Model :: RemoveFilteredPolicy(string sec, string p_type, int field_index, vector field_values) { +pair>> Model :: RemoveFilteredPolicy(string& sec, string& p_type, int field_index, vector field_values) { vector> tmp; vector> effects; vector> policy(m[sec].assertion_map[p_type]->policy); bool res = false; - for(int i = 0 ; i < policy.size() ; i++){ + for(size_t i = 0 ; i < policy.size() ; i++){ bool matched = true; - for (int j = 0 ; j < field_values.size() ; j++) { + for (size_t j = 0 ; j < field_values.size() ; j++) { if (field_values[j] != "" && (policy[i])[field_index+j] != field_values[j]) { matched = false; break; @@ -320,10 +320,10 @@ pair>> Model :: RemoveFilteredPolicy(string sec, str } // GetValuesForFieldInPolicy gets all values for a field for all rules in a policy, duplicated values are removed. -vector Model :: GetValuesForFieldInPolicy(string sec, string p_type, int field_index) { +vector Model :: GetValuesForFieldInPolicy(const string& sec,const string& p_type, int field_index) { vector values; vector> policy(m[sec].assertion_map[p_type]->policy); - for(int i = 0 ; i < policy.size() ; i++) + for(size_t i = 0 ; i < policy.size() ; i++) values.push_back((policy[i])[field_index]); ArrayRemoveDuplicates(values); @@ -332,12 +332,12 @@ vector Model :: GetValuesForFieldInPolicy(string sec, string p_type, int } // GetValuesForFieldInPolicyAllTypes gets all values for a field for all rules in a policy of all p_types, duplicated values are removed. -vector Model :: GetValuesForFieldInPolicyAllTypes(string sec, int field_index) { +vector Model :: GetValuesForFieldInPolicyAllTypes(const string& sec, int field_index) { vector values; - for (unordered_map> :: iterator it = m[sec].assertion_map.begin() ; it != m[sec].assertion_map.end() ; it++) { + for (unordered_map> :: iterator it = m[sec].assertion_map.begin() ; it != m[sec].assertion_map.end() ; ++it) { vector values_for_field(this->GetValuesForFieldInPolicy(sec, it->first, field_index)); - for(int i = 0 ; i < values_for_field.size() ; i++) + for(size_t i = 0 ; i < values_for_field.size() ; i++) values.push_back(values_for_field[i]); } diff --git a/casbin/model/model.h b/casbin/model/model.h index 98355c42..ea0c6009 100644 --- a/casbin/model/model.h +++ b/casbin/model/model.h @@ -37,33 +37,33 @@ class Model{ static unordered_map section_name_map; - static void LoadSection(Model* model, shared_ptr cfg, string sec); + static void LoadSection(Model* model, shared_ptr cfg,const string& sec); static string GetKeySuffix(int i); - static bool LoadAssertion(Model* model, shared_ptr cfg, string sec, string key); + static bool LoadAssertion(Model* model, shared_ptr cfg,const string& sec,const string& key); public: Model(); - Model(string path); + explicit Model(string& path); unordered_map m; // Minimal required sections for a model to be valid static vector required_sections; - bool HasSection(string sec); + bool HasSection(string& sec); // AddDef adds an assertion to the model. - bool AddDef(string sec, string key, string value); + bool AddDef(const string& sec,const string& key, string& value); // LoadModel loads the model from model CONF file. - void LoadModel(string path); + void LoadModel(string& path); // LoadModelFromText loads the model from the text. - void LoadModelFromText(string text); + void LoadModelFromText(string& text); void LoadModelFromConfig(shared_ptr cfg); @@ -74,12 +74,12 @@ class Model{ static Model* NewModel(); // NewModel creates a model from a .CONF file. - static Model* NewModelFromFile(string path); + static Model* NewModelFromFile(string& path); // NewModel creates a model from a string which contains model text. - static Model* NewModelFromString(string text); + static Model* NewModelFromString(string& text); - void BuildIncrementalRoleLinks(shared_ptr rm, policy_op op, string sec, string p_type, vector> rules); + void BuildIncrementalRoleLinks(shared_ptr rm, policy_op op,const string& sec, string& p_type, vector> rules); // BuildRoleLinks initializes the roles in RBAC. void BuildRoleLinks(shared_ptr rm); @@ -91,34 +91,34 @@ class Model{ void ClearPolicy(); // GetPolicy gets all rules in a policy. - vector> GetPolicy(string sec, string p_type); + vector> GetPolicy(const string& sec, string& p_type); // GetFilteredPolicy gets rules based on field filters from a policy. - vector> GetFilteredPolicy(string sec, string p_type, int field_index, vector field_values); + vector> GetFilteredPolicy(const string& sec, string& p_type, int field_index, vector field_values); // HasPolicy determines whether a model has the specified policy rule. - bool HasPolicy(string sec, string p_type, vector rule); + bool HasPolicy(const string& sec, string& p_type, vector& rule); // AddPolicy adds a policy rule to the model. - bool AddPolicy(string sec, string p_type, vector rule); + bool AddPolicy(string& sec, string& p_type, vector& rule); // AddPolicies adds policy rules to the model. - bool AddPolicies(string sec, string p_type, vector> rules); + bool AddPolicies(string& sec, string& p_type, vector> rules); // RemovePolicy removes a policy rule from the model. - bool RemovePolicy(string sec, string p_type, vector rule); + bool RemovePolicy(string& sec, string& p_type, vector& rule); // RemovePolicies removes policy rules from the model. - bool RemovePolicies(string sec, string p_type, vector> rules); + bool RemovePolicies(string& sec, string& p_type, vector> rules); // RemoveFilteredPolicy removes policy rules based on field filters from the model. - pair>> RemoveFilteredPolicy(string sec, string p_type, int field_index, vector field_values); + pair>> RemoveFilteredPolicy(string& sec, string& p_type, int field_index, vector field_values); // GetValuesForFieldInPolicy gets all values for a field for all rules in a policy, duplicated values are removed. - vector GetValuesForFieldInPolicy(string sec, string p_type, int field_index); + vector GetValuesForFieldInPolicy(const string& sec,const string& p_type, int field_index); // GetValuesForFieldInPolicyAllTypes gets all values for a field for all rules in a policy of all p_types, duplicated values are removed. - vector GetValuesForFieldInPolicyAllTypes(string sec, int field_index); + vector GetValuesForFieldInPolicyAllTypes(const string& sec, int field_index); }; #endif \ No newline at end of file diff --git a/casbin/model/scope_config.cpp b/casbin/model/scope_config.cpp index de97d4a8..b10e2896 100644 --- a/casbin/model/scope_config.cpp +++ b/casbin/model/scope_config.cpp @@ -70,122 +70,122 @@ void PushObjectValue(Scope scope){ duk_push_global_object(scope); } -void PushFunction(Scope scope, Function f, string fname, int nargs) { - duk_push_c_function(scope, f, (Index)nargs); +void PushFunction(Scope scope, Function f,const string& fname, int nargs) { + duk_push_c_function(scope, f, static_cast(nargs) ); duk_put_global_string(scope, fname.c_str()); } -void PushBoolean(Scope scope, bool expression, string identifier){ +void PushBoolean(Scope scope, bool expression, string& identifier){ duk_push_boolean(scope, expression); duk_put_global_string(scope, identifier.c_str()); } -void PushTrue(Scope scope, string identifier){ +void PushTrue(Scope scope, string& identifier){ duk_push_true(scope); duk_put_global_string(scope, identifier.c_str()); } -void PushFalse(Scope scope, string identifier){ +void PushFalse(Scope scope, string& identifier){ duk_push_false(scope); duk_put_global_string(scope, identifier.c_str()); } -void PushInt(Scope scope, int integer, string identifier){ +void PushInt(Scope scope, int integer, string& identifier){ duk_push_int(scope, integer); duk_put_global_string(scope, identifier.c_str()); } -void PushFloat(Scope scope, float f, string identifier){ +void PushFloat(Scope scope, float f, string& identifier){ duk_push_number(scope, f); duk_put_global_string(scope, identifier.c_str()); } -void PushDouble(Scope scope, double d, string identifier){ +void PushDouble(Scope scope, double d, string& identifier){ duk_push_number(scope, d); duk_put_global_string(scope, identifier.c_str()); } -void PushString(Scope scope, string s, string identifier){ +void PushString(Scope scope, string& s, string& identifier){ duk_push_string(scope, s.c_str()); duk_put_global_string(scope, identifier.c_str()); } -void PushPointer(Scope scope, void * ptr, string identifier){ +void PushPointer(Scope scope, void * ptr,const string& identifier){ duk_push_pointer(scope, ptr); duk_put_global_string(scope, identifier.c_str()); } -void PushObject(Scope scope, string identifier){ +void PushObject(Scope scope,const string& identifier){ duk_push_object(scope); duk_put_global_string(scope, identifier.c_str()); duk_push_int(scope, 0); duk_put_global_string(scope, (identifier+"len").c_str()); } -void PushFunctionPropToObject(Scope scope, string obj, Function f, string fname, int nargs) { +void PushFunctionPropToObject(Scope scope,const string& obj, Function f, string& fname, int nargs) { duk_get_global_string(scope, obj.c_str()); duk_push_c_function(scope, f, nargs); duk_put_prop_string(scope, -2, fname.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushBooleanPropToObject(Scope scope, string obj, bool expression, string identifier){ +void PushBooleanPropToObject(Scope scope,const string& obj, bool expression, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_boolean(scope, expression); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushTruePropToObject(Scope scope, string obj, string identifier){ +void PushTruePropToObject(Scope scope,const string& obj, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_true(scope); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushFalsePropToObject(Scope scope, string obj, string identifier){ +void PushFalsePropToObject(Scope scope,const string& obj, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_false(scope); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushIntPropToObject(Scope scope, string obj, int integer, string identifier){ +void PushIntPropToObject(Scope scope,const string& obj, int integer, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_int(scope, integer); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushFloatPropToObject(Scope scope, string obj, float f, string identifier){ +void PushFloatPropToObject(Scope scope,const string& obj, float f, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_number(scope, f); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushDoublePropToObject(Scope scope, string obj, double d, string identifier){ +void PushDoublePropToObject(Scope scope,const string& obj, double d, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_number(scope, d); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushStringPropToObject(Scope scope, string obj, string s, string identifier){ +void PushStringPropToObject(Scope scope,const string& obj,const string& s,const string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_string(scope, s.c_str()); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushPointerPropToObject(Scope scope, string obj, void * ptr, string identifier){ +void PushPointerPropToObject(Scope scope,const string& obj, void * ptr, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_push_pointer(scope, ptr); duk_put_prop_string(scope, -2, identifier.c_str()); duk_eval_string_noresult(scope, (obj+"len += 1;").c_str()); } -void PushObjectPropToObject(Scope scope, string obj, string identifier){ +void PushObjectPropToObject(Scope scope,const string& obj, string& identifier){ duk_get_global_string(scope, obj.c_str()); duk_get_global_string(scope, identifier.c_str()); duk_put_prop_string(scope, -2, identifier.c_str()); @@ -199,48 +199,48 @@ Type CheckType(Scope scope){ return Type::Float; } -bool FetchIdentifier(Scope scope, string identifier){ +bool FetchIdentifier(Scope scope,const string& identifier){ return duk_get_global_string(scope, identifier.c_str()); } unsigned int Size(Scope scope){ - return (unsigned int)duk_get_top(scope); + return static_cast(duk_get_top(scope)); } bool GetBoolean(Scope scope, int id){ - return bool(duk_to_boolean(scope, (Index)id)); + return static_cast(duk_to_boolean(scope, static_cast(id))); } int GetInt(Scope scope, int id){ - return int(duk_to_number(scope, (Index)id)); + return static_cast(duk_to_number(scope, static_cast(id))); } float GetFloat(Scope scope, int id){ - return float(duk_to_number(scope, (Index)id)); + return static_cast(duk_to_number(scope, static_cast(id))); } double GetDouble(Scope scope, int id){ - return double(duk_to_number(scope, (Index)id)); + return static_cast(duk_to_number(scope, static_cast(id))); } string GetString(Scope scope, int id){ - return string(duk_to_string(scope, (Index)id)); + return static_cast(duk_to_string(scope, static_cast(id))); } void* GetPointer(Scope scope, int id){ - return (void *)duk_to_pointer(scope, (Index)id); + return static_cast(duk_to_pointer(scope, static_cast(id))); } -void Get(Scope scope, string identifier){ +void Get(Scope scope,const string& identifier){ Eval(scope, identifier); } -bool Eval(Scope scope, string expression){ +bool Eval(Scope scope,const string& expression){ PushStringValue(scope, expression); return duk_peval(scope)==0; } -void EvalNoResult(Scope scope, string expression){ +void EvalNoResult(Scope scope, string& expression){ duk_eval_string_noresult(scope, expression.c_str()); } diff --git a/casbin/model/scope_config.h b/casbin/model/scope_config.h index 61ad456e..398dcda7 100644 --- a/casbin/model/scope_config.h +++ b/casbin/model/scope_config.h @@ -51,28 +51,28 @@ void PushDoubleValue(Scope scope, double d); void PushStringValue(Scope scope, string s); void PushPointerValue(Scope scope, void * ptr); void PushObjectValue(Scope scope); -void PushFunction(Scope scope, Function f, string fname, int nargs); -void PushBoolean(Scope scope, bool expression, string identifier); -void PushTrue(Scope scope, string identifier); -void PushFalse(Scope scope, string identifier); -void PushInt(Scope scope, int integer, string identifier); -void PushFloat(Scope scope, float f, string identifier); -void PushDouble(Scope scope, double d, string identifier); -void PushString(Scope scope, string s, string identifier); -void PushPointer(Scope scope, void * ptr, string identifier); -void PushObject(Scope scope, string identifier = "r"); -void PushFunctionPropToObject(Scope scope, string obj, Function f, string fname, int nargs); -void PushBooleanPropToObject(Scope scope, string obj, bool expression, string identifier); -void PushTruePropToObject(Scope scope, string obj, string identifier); -void PushFalsePropToObject(Scope scope, string obj, string identifier); -void PushIntPropToObject(Scope scope, string obj, int integer, string identifier); -void PushFloatPropToObject(Scope scope, string obj, float f, string identifier); -void PushDoublePropToObject(Scope scope, string obj, double d, string identifier); -void PushStringPropToObject(Scope scope, string obj, string s, string identifier); -void PushPointerPropToObject(Scope scope, string obj, void * ptr, string identifier); -void PushObjectPropToObject(Scope scope, string obj, string identifier); +void PushFunction(Scope scope, Function f,const string& fname, int nargs); +void PushBoolean(Scope scope, bool expression, string& identifier); +void PushTrue(Scope scope, string& identifier); +void PushFalse(Scope scope, string& identifier); +void PushInt(Scope scope, int integer, string& identifier); +void PushFloat(Scope scope, float f, string& identifier); +void PushDouble(Scope scope, double d, string& identifier); +void PushString(Scope scope, string& s, string& identifier); +void PushPointer(Scope scope, void * ptr,const string& identifier); +void PushObject(Scope scope,const string& identifier = "r"); +void PushFunctionPropToObject(Scope scope,const string& obj, Function f, string& fname, int nargs); +void PushBooleanPropToObject(Scope scope,const string& obj, bool expression, string& identifier); +void PushTruePropToObject(Scope scope,const string& obj, string& identifier); +void PushFalsePropToObject(Scope scope,const string& obj, string& identifier); +void PushIntPropToObject(Scope scope,const string& obj, int integer, string& identifier); +void PushFloatPropToObject(Scope scope,const string& obj, float f, string& identifier); +void PushDoublePropToObject(Scope scope,const string& obj, double d, string& identifier); +void PushStringPropToObject(Scope scope,const string& obj,const string& s,const string& identifier); +void PushPointerPropToObject(Scope scope,const string& obj, void * ptr, string& identifier); +void PushObjectPropToObject(Scope scope,const string& obj, string& identifier); Type CheckType(Scope scope); -bool FetchIdentifier(Scope scope, string identifier); +bool FetchIdentifier(Scope scope,const string& identifier); unsigned int Size(Scope scope); bool GetBoolean(Scope scope, int id = -1); int GetInt(Scope scope, int id = -1); @@ -80,8 +80,8 @@ float GetFloat(Scope scope, int id = -1); double GetDouble(Scope scope, int id = -1); string GetString(Scope scope, int id = -1); void* GetPointer(Scope scope, int id = -1); -void Get(Scope scope, string identifier); -bool Eval(Scope scope, string expression); -void EvalNoResult(Scope scope, string expression); +void Get(Scope scope,const string& identifier); +bool Eval(Scope scope,const string& expression); +void EvalNoResult(Scope scope, string& expression); #endif \ No newline at end of file diff --git a/casbin/persist/adapter.cpp b/casbin/persist/adapter.cpp index abc1cdee..18739ef9 100644 --- a/casbin/persist/adapter.cpp +++ b/casbin/persist/adapter.cpp @@ -25,11 +25,11 @@ // LoadPolicyLine loads a text line as a policy rule to model. void LoadPolicyLine(string line, Model* model) { - if(line == "" || line.find("#")==0) + if(line == "" || line.compare("#")==0) return; - vector tokens = Split(line, ",", -1); - for (int i = 0; i < tokens.size(); i++) + vector tokens = Split(line, ","); + for (size_t i = 0; i < tokens.size(); i++) tokens[i] = Trim(tokens[i]); string key = tokens[0]; @@ -42,4 +42,5 @@ void LoadPolicyLine(string line, Model* model) { (model->m[sec].assertion_map[key]->policy).push_back(new_tokens); } + #endif // ADAPTER_CPP diff --git a/casbin/persist/adapter.h b/casbin/persist/adapter.h index 8ec9ab50..10e30a6f 100644 --- a/casbin/persist/adapter.h +++ b/casbin/persist/adapter.h @@ -36,6 +36,7 @@ class Adapter { string file_path; bool filtered; + /** * LoadPolicy loads all policy rules from the storage. * @@ -43,6 +44,7 @@ class Adapter { */ virtual void LoadPolicy(Model* model) = 0; + /** * SavePolicy saves all policy rules to the storage. * @@ -58,7 +60,7 @@ class Adapter { * @param p_type the policy type, "p", "p2", .. or "g", "g2", .. * @param rule the rule, like (sub, obj, act). */ - virtual void AddPolicy(string sec, string p_type, vector rule) = 0; + virtual void AddPolicy(string& sec, string& p_type, vector& rule) = 0; /** * RemovePolicy removes a policy rule from the storage. @@ -68,7 +70,7 @@ class Adapter { * @param p_type the policy type, "p", "p2", .. or "g", "g2", .. * @param rule the rule, like (sub, obj, act). */ - virtual void RemovePolicy(string sec, string p_type, vector rule) = 0; + virtual void RemovePolicy(string& sec, string& p_type, vector& rule) = 0; /** * RemoveFilteredPolicy removes policy rules that match the filter from the storage. @@ -80,7 +82,7 @@ class Adapter { * @param field_values the field values to be matched, value "" * means not to match this field. */ - virtual void RemoveFilteredPolicy(string sec, string ptype, int field_index, vector field_values) = 0; + virtual void RemoveFilteredPolicy(string& sec, string& ptype, int field_index, vector& field_values) = 0; virtual bool IsFiltered() = 0; }; diff --git a/casbin/persist/default_watcher_ex.cpp b/casbin/persist/default_watcher_ex.cpp index f923e18e..9c021443 100644 --- a/casbin/persist/default_watcher_ex.cpp +++ b/casbin/persist/default_watcher_ex.cpp @@ -22,15 +22,15 @@ #include "./default_watcher_ex.h" -void DefaultWatcherEx :: UpdateForAddPolicy(vector params) { +void DefaultWatcherEx :: UpdateForAddPolicy(vector& params) { return; } -void DefaultWatcherEx :: UpdateForRemovePolicy(vector params) { +void DefaultWatcherEx :: UpdateForRemovePolicy(vector& params) { return; } -void DefaultWatcherEx :: UpdateForRemoveFilteredPolicy(int field_index, vector field_values) { +void DefaultWatcherEx :: UpdateForRemoveFilteredPolicy(int field_index, vector& field_values) { return; } diff --git a/casbin/persist/default_watcher_ex.h b/casbin/persist/default_watcher_ex.h index 3426a8c5..c1e89623 100644 --- a/casbin/persist/default_watcher_ex.h +++ b/casbin/persist/default_watcher_ex.h @@ -21,12 +21,12 @@ class DefaultWatcherEx: public WatcherEx { public: + ~DefaultWatcherEx()=default; + void UpdateForAddPolicy(vector& params); - void UpdateForAddPolicy(vector params); + void UpdateForRemovePolicy(vector& params); - void UpdateForRemovePolicy(vector params); - - void UpdateForRemoveFilteredPolicy(int field_index, vector field_values); + void UpdateForRemoveFilteredPolicy(int field_index, vector& field_values); void UpdateForSavePolicy(Model* model); }; diff --git a/casbin/persist/file_adapter/batch_file_adapter.cpp b/casbin/persist/file_adapter/batch_file_adapter.cpp index c2d53203..6f559f75 100644 --- a/casbin/persist/file_adapter/batch_file_adapter.cpp +++ b/casbin/persist/file_adapter/batch_file_adapter.cpp @@ -8,14 +8,14 @@ #include "../../exception/unsupported_operation_exception.h" // NewAdapter is the constructor for Adapter. -BatchFileAdapter :: BatchFileAdapter(string file_path): FileAdapter(file_path) { +BatchFileAdapter :: BatchFileAdapter(string& file_path): FileAdapter(file_path) { } -void BatchFileAdapter :: AddPolicies(string sec, string p_type, vector> rules) { +void BatchFileAdapter :: AddPolicies(string& sec, string& p_type, vector>& rules) { throw UnsupportedOperationException("not implemented hello"); } -void BatchFileAdapter :: RemovePolicies(string sec, string p_type, vector> rules) { +void BatchFileAdapter :: RemovePolicies(string& sec, string& p_type, vector>& rules) { throw UnsupportedOperationException("not implemented"); } diff --git a/casbin/persist/file_adapter/batch_file_adapter.h b/casbin/persist/file_adapter/batch_file_adapter.h index 70069cf0..801ae3b9 100644 --- a/casbin/persist/file_adapter/batch_file_adapter.h +++ b/casbin/persist/file_adapter/batch_file_adapter.h @@ -8,11 +8,11 @@ class BatchFileAdapter: public BatchAdapter, public FileAdapter { public: // NewAdapter is the constructor for Adapter. - BatchFileAdapter(string file_path); + explicit BatchFileAdapter(string& file_path); - void AddPolicies(string sec, string p_type, vector> rules); + void AddPolicies(string& sec, string& p_type, vector>& rules); - void RemovePolicies(string sec, string p_type, vector> rules); + void RemovePolicies(string& sec, string& p_type, vector>& rules); }; #endif \ No newline at end of file diff --git a/casbin/persist/file_adapter/file_adapter.cpp b/casbin/persist/file_adapter/file_adapter.cpp index 15ba383e..de9253b9 100644 --- a/casbin/persist/file_adapter/file_adapter.cpp +++ b/casbin/persist/file_adapter/file_adapter.cpp @@ -13,7 +13,7 @@ #include "../../exception/casbin_adapter_exception.h" // NewAdapter is the constructor for Adapter. -FileAdapter :: FileAdapter(string file_path) { +FileAdapter :: FileAdapter(string& file_path) { this->file_path = file_path; this->filtered = false; } @@ -34,16 +34,16 @@ void FileAdapter :: SavePolicy(Model* model) { string tmp; - for (unordered_map> :: iterator it = model->m["p"].assertion_map.begin() ; it != model->m["p"].assertion_map.begin() ; it++){ - for (int i = 0 ; i < it->second->policy.size() ; i++){ + for (unordered_map> :: iterator it = model->m["p"].assertion_map.begin() ; it != model->m["p"].assertion_map.begin() ; ++it){ + for (size_t i = 0 ; i < it->second->policy.size() ; i++){ tmp += it->first + ", "; tmp += ArrayToString(it->second->policy[i]); tmp += "\n"; } } - for (unordered_map > :: iterator it = model->m["g"].assertion_map.begin() ; it != model->m["g"].assertion_map.begin() ; it++){ - for (int i = 0 ; i < it->second->policy.size() ; i++){ + for (unordered_map > :: iterator it = model->m["g"].assertion_map.begin() ; it != model->m["g"].assertion_map.begin() ; ++it){ + for (size_t i = 0 ; i < it->second->policy.size() ; i++){ tmp += it->first + ", "; tmp += ArrayToString(it->second->policy[i]); tmp += "\n"; @@ -57,7 +57,7 @@ void FileAdapter :: LoadPolicyFile(Model* model, void (*handler)(string, Model*) ifstream in_file; try { in_file.open(this->file_path); - } catch (const ifstream::failure e) { + } catch (const ifstream::failure& e) { throw IOException("Cannot open file."); } @@ -70,12 +70,12 @@ void FileAdapter :: LoadPolicyFile(Model* model, void (*handler)(string, Model*) in_file.close(); } -void FileAdapter :: SavePolicyFile(string text) { +void FileAdapter :: SavePolicyFile(string& text) { ofstream out_file; out_file.open(this->file_path,ios::out); try { out_file.open(this->file_path,ios::out); - } catch (const ifstream::failure e) { + } catch (const ifstream::failure& e) { throw IOException("Cannot open file."); } @@ -85,17 +85,17 @@ void FileAdapter :: SavePolicyFile(string text) { } // AddPolicy adds a policy rule to the storage. -void FileAdapter :: AddPolicy(string sec, string p_type, vector rule) { +void FileAdapter :: AddPolicy(string& sec, string& p_type, vector& rule) { throw UnsupportedOperationException("not implemented"); } // RemovePolicy removes a policy rule from the storage. -void FileAdapter :: RemovePolicy(string sec, string p_type, vector rule) { +void FileAdapter :: RemovePolicy(string& sec, string& p_type, vector& rule) { throw UnsupportedOperationException("not implemented"); } // RemoveFilteredPolicy removes policy rules that match the filter from the storage. -void FileAdapter :: RemoveFilteredPolicy(string sec, string p_type, int field_index, vector field_values) { +void FileAdapter :: RemoveFilteredPolicy(string& sec, string& p_type, int field_index, vector& field_values) { throw UnsupportedOperationException("not implemented"); } diff --git a/casbin/persist/file_adapter/file_adapter.h b/casbin/persist/file_adapter/file_adapter.h index 75f67166..27c0088a 100644 --- a/casbin/persist/file_adapter/file_adapter.h +++ b/casbin/persist/file_adapter/file_adapter.h @@ -5,11 +5,13 @@ // Adapter is the file adapter for Casbin. // It can load policy from file or save policy to file. -class FileAdapter : virtual public Adapter { +class FileAdapter :virtual public Adapter { public: // NewAdapter is the constructor for Adapter. - FileAdapter(string file_path); + explicit FileAdapter(string& file_path); + + ~FileAdapter()=default; // LoadPolicy loads all policy rules from the storage. void LoadPolicy(Model* model); @@ -19,16 +21,16 @@ class FileAdapter : virtual public Adapter { void LoadPolicyFile(Model* model, void (*handler)(string, Model*)); - void SavePolicyFile(string text); + void SavePolicyFile(string& text); // AddPolicy adds a policy rule to the storage. - void AddPolicy(string sec, string p_type, vector rule); + void AddPolicy(string& sec, string& p_type, vector& rule); // RemovePolicy removes a policy rule from the storage. - void RemovePolicy(string sec, string p_type, vector rule); + void RemovePolicy(string& sec, string& p_type, vector& rule); // RemoveFilteredPolicy removes policy rules that match the filter from the storage. - void RemoveFilteredPolicy(string sec, string p_type, int field_index, vector field_values); + void RemoveFilteredPolicy(string& sec, string& p_type, int field_index, vector& field_values); // IsFiltered returns true if the loaded policy has been filtered. bool IsFiltered(); diff --git a/casbin/persist/file_adapter/filtered_file_adapter.cpp b/casbin/persist/file_adapter/filtered_file_adapter.cpp index 46a46174..b4b3542e 100644 --- a/casbin/persist/file_adapter/filtered_file_adapter.cpp +++ b/casbin/persist/file_adapter/filtered_file_adapter.cpp @@ -13,7 +13,7 @@ using namespace std; -bool FilteredFileAdapter :: filterLine(string line, Filter* filter) { +bool FilteredFileAdapter :: filterLine(string& line, Filter* filter) { if (filter == NULL) return false; @@ -35,8 +35,8 @@ bool FilteredFileAdapter :: filterWords(vector line, vector filt if (line.size() < filter.size()+1) return true; - bool skip_line; - for (int i = 0 ; i < filter.size() ; i++) { + bool skip_line= false; + for (size_t i = 0 ; i < filter.size() ; i++) { if (filter[i].length()>0 && Trim(filter[i]) != Trim(line[i+1])) { skip_line = true; break; @@ -50,7 +50,7 @@ void FilteredFileAdapter :: loadFilteredPolicyFile(Model* model, Filter* filter, ifstream out_file; try { out_file.open(this->file_path); - } catch (const ifstream::failure e) { + } catch (const ifstream::failure& e) { throw IOException("Cannot open file."); } @@ -67,8 +67,9 @@ void FilteredFileAdapter :: loadFilteredPolicyFile(Model* model, Filter* filter, out_file.close(); } + // NewFilteredAdapter is the constructor for FilteredAdapter. -FilteredFileAdapter :: FilteredFileAdapter(string file_path): FileAdapter(file_path) { +FilteredFileAdapter :: FilteredFileAdapter(string& file_path): FileAdapter(file_path) { this->filtered = true; } @@ -80,7 +81,7 @@ void FilteredFileAdapter :: LoadPolicy(Model* model) { // LoadFilteredPolicy loads only policy rules that match the filter. void FilteredFileAdapter :: LoadFilteredPolicy(Model* model, Filter* filter) { - if (filter == NULL) { + if (filter == nullptr) { this->LoadPolicy(model); } diff --git a/casbin/persist/file_adapter/filtered_file_adapter.h b/casbin/persist/file_adapter/filtered_file_adapter.h index 779815fc..25f82f3b 100644 --- a/casbin/persist/file_adapter/filtered_file_adapter.h +++ b/casbin/persist/file_adapter/filtered_file_adapter.h @@ -7,7 +7,7 @@ class FilteredFileAdapter : public FileAdapter, public FilteredAdapter { private: - static bool filterLine(string line, Filter* filter); + static bool filterLine(string& line, Filter* filter); static bool filterWords(vector line, vector filter); @@ -16,7 +16,7 @@ class FilteredFileAdapter : public FileAdapter, public FilteredAdapter { public: // NewFilteredAdapter is the constructor for FilteredAdapter. - FilteredFileAdapter(string file_path); + explicit FilteredFileAdapter(string& file_path); // LoadPolicy loads all policy rules from the storage. void LoadPolicy(Model* model); diff --git a/casbin/persist/filtered_adapter.h b/casbin/persist/filtered_adapter.h index 70f29e18..9767b209 100644 --- a/casbin/persist/filtered_adapter.h +++ b/casbin/persist/filtered_adapter.h @@ -28,9 +28,8 @@ class Filter{ }; // FilteredAdapter is the interface for Casbin adapters supporting filtered policies. -class FilteredAdapter : virtual public Adapter { +class FilteredAdapter :virtual public Adapter { public: - // LoadFilteredPolicy loads only policy rules that match the filter. void LoadFilteredPolicy(Model* model, Filter* filter); // IsFiltered returns true if the loaded policy has been filtered. diff --git a/casbin/persist/watcher.h b/casbin/persist/watcher.h index 5bc93116..fc9e5429 100644 --- a/casbin/persist/watcher.h +++ b/casbin/persist/watcher.h @@ -24,7 +24,7 @@ using namespace std; // Watcher is the interface for Casbin watchers. class Watcher { public: - + virtual ~Watcher()=0; // SetUpdateCallback sets the callback function that the watcher will call // when the policy in DB has been changed by other instances. // A classic callback is Enforcer.LoadPolicy(). diff --git a/casbin/persist/watcher_ex.h b/casbin/persist/watcher_ex.h index c020e034..36bd8ec3 100644 --- a/casbin/persist/watcher_ex.h +++ b/casbin/persist/watcher_ex.h @@ -23,13 +23,14 @@ // WatcherEx is the strengthen for Casbin watchers. class WatcherEx: public Watcher { public: + ~WatcherEx()=default; // UpdateForAddPolicy calls the update callback of other instances to synchronize their policy. // It is called after Enforcer.AddPolicy() - virtual void UpdateForAddPolicy(vector params) = 0; + virtual void UpdateForAddPolicy(vector& params) = 0; // UPdateForRemovePolicy calls the update callback of other instances to synchronize their policy. // It is called after Enforcer.RemovePolicy() - virtual void UpdateForRemovePolicy(vector params) = 0; + virtual void UpdateForRemovePolicy(vector& params) = 0; // UpdateForRemoveFilteredPolicy calls the update callback of other instances to synchronize their policy. // It is called after Enforcer.RemoveFilteredNamedGroupingPolicy() diff --git a/casbin/rbac/default_role_manager.cpp b/casbin/rbac/default_role_manager.cpp index 1e0d2012..5eb4e487 100644 --- a/casbin/rbac/default_role_manager.cpp +++ b/casbin/rbac/default_role_manager.cpp @@ -23,14 +23,15 @@ #include "./default_role_manager.h" #include "../exception/casbin_rbac_exception.h" -Role* Role :: NewRole(string name) { +Role* Role :: NewRole(const string& name) { Role* role = new Role; role->name = name; return role; } + void Role :: AddRole(Role* role) { - for (int i = 0 ; i < this->roles.size() ; i++) { + for (size_t i = 0 ; i < this->roles.size() ; i++) { if (this->roles[i]->name == role->name) return; } @@ -39,7 +40,7 @@ void Role :: AddRole(Role* role) { } void Role :: DeleteRole(Role* role) { - for (int i = 0; i < roles.size();i++) { + for (size_t i = 0; i < roles.size();i++) { if (roles[i]->name == role->name) roles.erase(roles.begin()+i); } @@ -52,7 +53,7 @@ bool Role :: HasRole(string name, int hierarchy_level) { if (hierarchy_level <= 0) return false; - for(int i = 0 ; i < roles.size() ; i++){ + for(size_t i = 0 ; i < roles.size() ; i++){ if (roles[i]->HasRole(name, hierarchy_level - 1)) return true; } @@ -60,8 +61,8 @@ bool Role :: HasRole(string name, int hierarchy_level) { return false; } -bool Role :: HasDirectRole(string name) { - for(int i = 0 ; i < roles.size() ; i++){ +bool Role :: HasDirectRole(string& name) { + for(size_t i = 0 ; i < roles.size() ; i++){ if (roles[i]->name == name) return true; } @@ -77,7 +78,7 @@ string Role :: ToString() { if(this->roles.size() != 1) names += "("; - for (int i = 0; i < roles.size(); i ++) { + for (size_t i = 0; i < roles.size(); i ++) { Role* role = roles[i]; if (i == 0) names += role->name; @@ -93,7 +94,7 @@ string Role :: ToString() { vector Role :: GetRoles() { vector names; - for(int i = 0 ; i < roles.size() ; i++) + for(size_t i = 0 ; i < roles.size() ; i++) names.push_back(roles[i]->name); return names; @@ -102,7 +103,7 @@ vector Role :: GetRoles() { bool DefaultRoleManager :: HasRole(string name) { bool ok = false; if (this->has_pattern){ - for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; it++){ + for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; ++it){ if (this->matching_func(name, it->first)) ok = true; } @@ -123,7 +124,7 @@ Role* DefaultRoleManager :: CreateRole(string name) { role = all_roles[name]; if (this->has_pattern) { - for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; it++){ + for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; ++it){ if (this->matching_func(name, it->first) && name!=it->first) { Role* role1; bool ok1 = this->all_roles.find(it->first) != this->all_roles.end(); @@ -146,9 +147,7 @@ Role* DefaultRoleManager :: CreateRole(string name) { * * @param max_hierarchy_level the maximized allowed RBAC hierarchy level. */ -DefaultRoleManager :: DefaultRoleManager(int max_hierarchy_level) { - this->max_hierarchy_level = max_hierarchy_level; - this->has_pattern = false; +DefaultRoleManager :: DefaultRoleManager(int max_hierarchy_level):has_pattern(false), max_hierarchy_level(max_hierarchy_level) { } // e.BuildRoleLinks must be called after AddMatchingFunc(). @@ -187,7 +186,7 @@ void DefaultRoleManager :: AddLink(string name1, string name2, vector do * domain is a prefix to the roles. */ void DefaultRoleManager :: DeleteLink(string name1, string name2, vector domain) { - unsigned int domain_length = int(domain.size()); + auto domain_length = domain.size(); if (domain_length == 1) { name1 = domain[0] + "::" + name1; name2 = domain[0] + "::" + name2; @@ -207,7 +206,7 @@ void DefaultRoleManager :: DeleteLink(string name1, string name2, vector * domain is a prefix to the roles. */ bool DefaultRoleManager :: HasLink(string name1, string name2, vector domain) { - unsigned int domain_length = int(domain.size()); + auto domain_length = domain.size(); if (domain_length == 1) { name1 = domain[0] + "::" + name1; name2 = domain[0] + "::" + name2; @@ -228,7 +227,7 @@ bool DefaultRoleManager :: HasLink(string name1, string name2, vector do * domain is a prefix to the roles. */ vector DefaultRoleManager :: GetRoles(string name, vector domain) { - unsigned int domain_length = int(domain.size()); + auto domain_length = domain.size(); if (domain_length == 1) name = domain[0] + "::" + name; else if (domain_length > 1) @@ -241,7 +240,7 @@ vector DefaultRoleManager :: GetRoles(string name, vector domain vector roles = this->CreateRole(name)->GetRoles(); if (domain_length == 1){ - for (int i = 0; i < roles.size(); i ++) + for (size_t i = 0; i < roles.size(); i ++) roles[i] = roles[i].substr(domain[0].length() + 2, roles[i].length() - domain[0].length() - 2); } @@ -258,14 +257,14 @@ vector DefaultRoleManager :: GetUsers(string name, vector domain throw CasbinRBACException("error: name does not exist"); vector names; - for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; it++){ + for (unordered_map :: iterator it = this->all_roles.begin() ; it != this->all_roles.end() ; ++it){ Role* role = it->second; if (role->HasDirectRole(name)) names.push_back(role->name); } if (domain.size() == 1){ - for (int i = 0 ; i < names.size() ; i++) + for (size_t i = 0 ; i < names.size() ; i++) names[i] = names[i].substr(domain[0].length() + 2, names[i].length() - domain[0].length() - 2); } @@ -284,8 +283,8 @@ void DefaultRoleManager :: PrintRoles() { string text = this->all_roles.begin()->second->ToString(); unordered_map :: iterator it = this->all_roles.begin(); - it++; - for ( ; it != this->all_roles.end() ; it++) + ++it; + for ( ; it != this->all_roles.end() ; ++it) text += ", " + it->second->ToString(); // LogUtil::LogPrint(text); } diff --git a/casbin/rbac/default_role_manager.h b/casbin/rbac/default_role_manager.h index 12d977e7..25397f67 100644 --- a/casbin/rbac/default_role_manager.h +++ b/casbin/rbac/default_role_manager.h @@ -18,7 +18,6 @@ #define CASBIN_CPP_RBAC_DEFAULT_ROLE_MANAGER #include - #include "./role_manager.h" using namespace std; @@ -36,7 +35,7 @@ class Role { public: string name; - static Role* NewRole(string name); + static Role* NewRole(const string& name); void AddRole(Role* role); @@ -44,7 +43,7 @@ class Role { bool HasRole(string name, int hierarchy_level); - bool HasDirectRole(string name); + bool HasDirectRole(string& name); string ToString(); @@ -70,7 +69,7 @@ class DefaultRoleManager : public RoleManager { * * @param max_hierarchy_level the maximized allowed RBAC hierarchy level. */ - DefaultRoleManager(int max_hierarchy_level); + explicit DefaultRoleManager(int max_hierarchy_level); // e.BuildRoleLinks must be called after AddMatchingFunc(). // diff --git a/casbin/rbac_api.cpp b/casbin/rbac_api.cpp index 82096cb3..1a85c410 100644 --- a/casbin/rbac_api.cpp +++ b/casbin/rbac_api.cpp @@ -37,7 +37,7 @@ vector Enforcer :: GetUsersForRole(string name, vector domain) { } // HasRoleForUser determines whether a user has a role. -bool Enforcer :: HasRoleForUser(string name, string role) { +bool Enforcer :: HasRoleForUser(string name, string& role) { vector domain; vector roles = this->GetRolesForUser(name, domain); @@ -54,14 +54,14 @@ bool Enforcer :: HasRoleForUser(string name, string role) { // AddRoleForUser adds a role for a user. // Returns false if the user already has the role (aka not affected). -bool Enforcer :: AddRoleForUser(string user, string role) { +bool Enforcer :: AddRoleForUser(string& user, string& role) { vector params{user, role}; return this->AddGroupingPolicy(params); } // AddRolesForUser adds roles for a user. // Returns false if the user already has the roles (aka not affected). -bool Enforcer :: AddRolesForUser(string user, vector roles) { +bool Enforcer :: AddRolesForUser(string& user, vector roles) { bool f = false; for(int i=0;iAddGroupingPolicy({user, roles[i]}); @@ -73,21 +73,21 @@ bool Enforcer :: AddRolesForUser(string user, vector roles) { // DeleteRoleForUser deletes a role for a user. // Returns false if the user does not have the role (aka not affected). -bool Enforcer :: DeleteRoleForUser(string user, string role) { +bool Enforcer :: DeleteRoleForUser(string& user, string& role) { vector params{user, role}; return this->RemoveGroupingPolicy(params); } // DeleteRolesForUser deletes all roles for a user. // Returns false if the user does not have any roles (aka not affected). -bool Enforcer :: DeleteRolesForUser(string user) { +bool Enforcer :: DeleteRolesForUser(string& user) { vector field_values{user}; return this->RemoveFilteredGroupingPolicy(0, field_values); } // DeleteUser deletes a user. // Returns false if the user does not exist (aka not affected). -bool Enforcer :: DeleteUser(string user) { +bool Enforcer :: DeleteUser(string& user) { vector field_values{user}; bool res1 = this->RemoveFilteredGroupingPolicy(0, field_values); @@ -99,7 +99,7 @@ bool Enforcer :: DeleteUser(string user) { // DeleteRole deletes a role. // Returns false if the role does not exist (aka not affected). -bool Enforcer :: DeleteRole(string role) { +bool Enforcer :: DeleteRole(string& role) { vector field_values{role}; bool res1 = this->RemoveFilteredGroupingPolicy(1, field_values); @@ -111,38 +111,38 @@ bool Enforcer :: DeleteRole(string role) { // DeletePermission deletes a permission. // Returns false if the permission does not exist (aka not affected). -bool Enforcer :: DeletePermission(vector permission) { +bool Enforcer :: DeletePermission(vector& permission) { vector field_values{permission}; return this->RemoveFilteredPolicy(1, field_values); } // AddPermissionForUser adds a permission for a user or role. // Returns false if the user or role already has the permission (aka not affected). -bool Enforcer :: AddPermissionForUser(string user, vector permission) { +bool Enforcer :: AddPermissionForUser(string& user, vector& permission) { return this->AddPolicy(JoinSlice(user, permission)); } // DeletePermissionForUser deletes a permission for a user or role. // Returns false if the user or role does not have the permission (aka not affected). -bool Enforcer :: DeletePermissionForUser(string user, vector permission) { +bool Enforcer :: DeletePermissionForUser(string user, vector& permission) { return this->RemovePolicy(JoinSlice(user, permission)); } // DeletePermissionsForUser deletes permissions for a user or role. // Returns false if the user or role does not have any permissions (aka not affected). -bool Enforcer :: DeletePermissionsForUser(string user) { +bool Enforcer :: DeletePermissionsForUser(string& user) { vector field_values{user}; return this->RemoveFilteredPolicy(0, field_values); } // GetPermissionsForUser gets permissions for a user or role. -vector> Enforcer :: GetPermissionsForUser(string user) { +vector> Enforcer :: GetPermissionsForUser(string& user) { vector field_values{user}; return this->GetFilteredPolicy(0, field_values); } // HasPermissionForUser determines whether a user has a permission. -bool Enforcer :: HasPermissionForUser(string user, vector permission) { +bool Enforcer :: HasPermissionForUser(string& user, vector& permission) { return this->HasPolicy(JoinSlice(user, permission)); } diff --git a/casbin/rbac_api_with_domains.cpp b/casbin/rbac_api_with_domains.cpp index 0efb8631..32f0fe64 100644 --- a/casbin/rbac_api_with_domains.cpp +++ b/casbin/rbac_api_with_domains.cpp @@ -23,35 +23,35 @@ #include "./enforcer.h" // GetUsersForRoleInDomain gets the users that has a role inside a domain. Add by Gordon -vector Enforcer :: GetUsersForRoleInDomain(string name, string domain) { +vector Enforcer :: GetUsersForRoleInDomain(string name, string& domain) { vector domains{domain}; vector res = this->model->m["g"].assertion_map["g"]->rm->GetUsers(name, domains); return res; } // GetRolesForUserInDomain gets the roles that a user has inside a domain. -vector Enforcer :: GetRolesForUserInDomain(string name, string domain) { +vector Enforcer :: GetRolesForUserInDomain(string name, string& domain) { vector domains{domain}; vector res = this->model->m["g"].assertion_map["g"]->rm->GetRoles(name, domains); return res; } // GetPermissionsForUserInDomain gets permissions for a user or role inside a domain. -vector> Enforcer :: GetPermissionsForUserInDomain(string user, string domain) { +vector> Enforcer :: GetPermissionsForUserInDomain(string& user, string& domain) { vector field_values{user, domain}; return this->GetFilteredPolicy(0, field_values); } // AddRoleForUserInDomain adds a role for a user inside a domain. // Returns false if the user already has the role (aka not affected). -bool Enforcer :: AddRoleForUserInDomain(string user, string role, string domain) { +bool Enforcer :: AddRoleForUserInDomain(string& user, string& role, string& domain) { vector params{user, role, domain}; return this->AddGroupingPolicy(params); } // DeleteRoleForUserInDomain deletes a role for a user inside a domain. // Returns false if the user does not have the role (aka not affected). -bool Enforcer :: DeleteRoleForUserInDomain(string user, string role, string domain) { +bool Enforcer :: DeleteRoleForUserInDomain(string& user, string& role, string& domain) { vector params{user, role, domain}; return this->RemoveGroupingPolicy(params); } diff --git a/casbin/util/built_in_functions.cpp b/casbin/util/built_in_functions.cpp index cd323de7..74b70ca7 100644 --- a/casbin/util/built_in_functions.cpp +++ b/casbin/util/built_in_functions.cpp @@ -66,19 +66,19 @@ ReturnType KeyMatch2(Scope scope) { return RETURN_RESULT; } -bool KeyMatch2(string key1, string key2) { +bool KeyMatch2(string& key1, string& key2) { vector key1_arr = Split(key1, "/"); vector key2_arr = Split(key2, "/"); bool res = true; - for(int i=0;i= key1_arr.size()){ res = false; break; } if(key1_arr[i] != key2_arr[i]){ - int index1 = int(key2_arr[i].find("*")); - int index2 = int(key2_arr[i].find(":")); + size_t index1 = key2_arr[i].find("*"); + size_t index2 = key2_arr[i].find(":"); if(index1 != string::npos){ if(index1==0){ res = true; @@ -120,7 +120,7 @@ ReturnType KeyMatch3(Scope scope) { return RETURN_RESULT; } -bool KeyMatch3(string key1, string key2) { +bool KeyMatch3(string& key1, string& key2) { vector key1_arr = Split(key1, "/"); vector key2_arr = Split(key2, "/"); @@ -189,7 +189,7 @@ ReturnType IPMatch(Scope scope) { return RETURN_RESULT; } -bool IPMatch(string ip1, string ip2) { +bool IPMatch(string& ip1, string& ip2) { IP objIP1 = parseIP(ip1); if (objIP1.isLegal == false) throw IllegalArgumentException("invalid argument: ip1 in IPMatch() function is not an IP address."); @@ -209,7 +209,7 @@ bool IPMatch(string ip1, string ip2) { // GFunction is the method of the g(_, _) function. ReturnType GFunction(Scope scope) { RoleManager* rm; - rm = (RoleManager*)GetPointer(scope, 0); + rm = static_cast(GetPointer(scope, 0)); string name1 = GetString(scope, 1); string name2 = GetString(scope, 2); diff --git a/casbin/util/built_in_functions.h b/casbin/util/built_in_functions.h index fc405b66..0a70aa14 100644 --- a/casbin/util/built_in_functions.h +++ b/casbin/util/built_in_functions.h @@ -27,12 +27,12 @@ bool KeyMatch(string key1, string key2); // KeyMatch2 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. // For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/:resource" ReturnType KeyMatch2(Scope scope); -bool KeyMatch2(string key1, string key2); +bool KeyMatch2(string& key1, string& key2); // KeyMatch3 determines whether key1 matches the pattern of key2 (similar to RESTful path), key2 can contain a *. // For example, "/foo/bar" matches "/foo/*", "/resource1" matches "/{resource}" ReturnType KeyMatch3(Scope scope); -bool KeyMatch3(string key1, string key2); +bool KeyMatch3(string& key1, string& key2); // RegexMatch determines whether key1 matches the pattern of key2 in regular expression. ReturnType RegexMatch(Scope scope); @@ -41,7 +41,7 @@ bool RegexMatch(string key1, string key2); // IPMatch determines whether IP address ip1 matches the pattern of IP address ip2, ip2 can be an IP address or a CIDR pattern. // For example, "192.168.2.123" matches "192.168.2.0/24" ReturnType IPMatch(Scope scope); -bool IPMatch(string ip1, string ip2); +bool IPMatch(string& ip1, string& ip2); // GFunction is the method of the g(_, _) function. ReturnType GFunction(Scope scope); diff --git a/casbin/util/ends_with.cpp b/casbin/util/ends_with.cpp index 062094fc..63762015 100644 --- a/casbin/util/ends_with.cpp +++ b/casbin/util/ends_with.cpp @@ -25,8 +25,8 @@ using namespace std; bool EndsWith(string base, string suffix){ - int base_len = int(base.length()); - int suffix_len = int(suffix.length()); + string::size_type base_len = base.length(); + string::size_type suffix_len = suffix.length(); return base.substr(base_len-suffix_len, suffix_len).compare(suffix) == 0; } diff --git a/casbin/util/join.cpp b/casbin/util/join.cpp index 17e5ed98..4a5b71fa 100644 --- a/casbin/util/join.cpp +++ b/casbin/util/join.cpp @@ -24,7 +24,7 @@ using namespace std; -string Join(vector vos, string sep){ +string Join(vector vos,const string& sep){ string fs = vos[0]; for (int i = 1 ; i < vos.size() ; i++) fs += sep + vos[i]; diff --git a/casbin/util/join_slice.cpp b/casbin/util/join_slice.cpp index 86ce2622..dc3546fb 100644 --- a/casbin/util/join_slice.cpp +++ b/casbin/util/join_slice.cpp @@ -24,7 +24,7 @@ using namespace std; -vector JoinSlice(string a, vector slice) { +vector JoinSlice(string& a, vector slice) { vector result{a}; for (int i = 0 ; i < slice.size() ; i++) result.push_back(slice[i]); diff --git a/casbin/util/split.cpp b/casbin/util/split.cpp index ad40235c..d404702e 100644 --- a/casbin/util/split.cpp +++ b/casbin/util/split.cpp @@ -28,23 +28,17 @@ using namespace std; -vector Split(string str, string del, int limit){ - vector tokens; - - if(limit<=0) - limit = LARGE; - - for (int i = 1; i < limit ; i++) { - size_t pos = str.find(del); - if (pos != string::npos) { - tokens.push_back(str.substr(0, pos)); - str = str.substr(pos + del.length()); - } else - break; - } - tokens.push_back(str); - return tokens; +vector Split(const string& src,const string& del) { + string::size_type start=src.find_first_not_of(del,0); + string::size_type pos=src.find_first_of(del,start); + vector dest; + while(string::npos != pos || string::npos != start) { + dest.emplace_back(src.substr(start,pos-start)); + start=src.find_first_not_of(del,pos); + pos=src.find_first_of(del,start); + } + return dest; } #endif // SPLIT_CPP diff --git a/casbin/util/trim.cpp b/casbin/util/trim.cpp index d9580aa4..6eefe53d 100644 --- a/casbin/util/trim.cpp +++ b/casbin/util/trim.cpp @@ -34,7 +34,7 @@ string& RTrim(string& str, const string& chars) { return str; } -string Trim(string& str, const string& chars) { +const string& Trim(string& str, const string& chars) { return LTrim(RTrim(str, chars), chars); } diff --git a/casbin/util/util.h b/casbin/util/util.h index 7fd700c2..a1f7c3d4 100644 --- a/casbin/util/util.h +++ b/casbin/util/util.h @@ -45,9 +45,9 @@ vector FindAllOccurences(string data, string toSearch); template bool IsInstanceOf(const T*); -vector JoinSlice(string a, vector slice); +vector JoinSlice(string& a, vector slice); -string Join(vector vos, string sep = " "); +string Join(vector vos,const string& sep = " "); // RemoveComments removes the comments starting with # in the text. string RemoveComments(string s); @@ -55,12 +55,13 @@ string RemoveComments(string s); // SetSubtract returns the elements in `a` that aren't in `b`. vector SetSubtract(vector a, vector b); -vector Split(string str, string del, int limit = 0); +//vector Split(string str, string del, int limit = 0); +vector Split(const string& src,const string& del); string& LTrim(string& str, const string& chars = "\t\n\v\f\r "); string& RTrim(string& str, const string& chars = "\t\n\v\f\r "); -string Trim(string& str, const string& chars = "\t\n\v\f\r "); +const string& Trim(string& str, const string& chars = "\t\n\v\f\r "); #endif \ No newline at end of file