Skip to content

Commit 79a635b

Browse files
authored
feat: optimize the complexity of RemovePolicy from O(n) to O(1) (#1485)
1 parent cbeafe9 commit 79a635b

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

management_api_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ func testGetPolicy(t *testing.T, e *Enforcer, res [][]string) {
6161

6262
t.Log("Policy: ", myRes)
6363

64-
if !util.Array2DEquals(res, myRes) {
64+
if !util.SortedArray2DEquals(res, myRes) {
6565
t.Error("Policy: ", myRes, ", supposed to be ", res)
6666
}
6767
}

model/policy.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -281,22 +281,25 @@ func (model Model) AddPoliciesWithAffected(sec string, ptype string, rules [][]s
281281
// RemovePolicy removes a policy rule from the model.
282282
// Deprecated: Using AddPoliciesWithAffected instead.
283283
func (model Model) RemovePolicy(sec string, ptype string, rule []string) (bool, error) {
284-
_, err := model.GetAssertion(sec, ptype)
284+
ast, err := model.GetAssertion(sec, ptype)
285285
if err != nil {
286286
return false, err
287287
}
288-
index, ok := model[sec][ptype].PolicyMap[strings.Join(rule, DefaultSep)]
288+
key := strings.Join(rule, DefaultSep)
289+
index, ok := ast.PolicyMap[key]
289290
if !ok {
290-
return false, err
291+
return false, nil
291292
}
292293

293-
model[sec][ptype].Policy = append(model[sec][ptype].Policy[:index], model[sec][ptype].Policy[index+1:]...)
294-
delete(model[sec][ptype].PolicyMap, strings.Join(rule, DefaultSep))
295-
for i := index; i < len(model[sec][ptype].Policy); i++ {
296-
model[sec][ptype].PolicyMap[strings.Join(model[sec][ptype].Policy[i], DefaultSep)] = i
294+
lastIdx := len(ast.Policy) - 1
295+
if index != lastIdx {
296+
ast.Policy[index] = ast.Policy[lastIdx]
297+
lastPolicyKey := strings.Join(ast.Policy[index], DefaultSep)
298+
ast.PolicyMap[lastPolicyKey] = index
297299
}
298-
299-
return true, err
300+
ast.Policy = ast.Policy[:lastIdx]
301+
delete(ast.PolicyMap, key)
302+
return true, nil
300303
}
301304

302305
// UpdatePolicy updates a policy rule from the model.

0 commit comments

Comments
 (0)