@@ -344,24 +344,47 @@ func (model Model) RemovePolicies(sec string, ptype string, rules [][]string) (b
344344
345345// RemovePoliciesWithAffected removes policy rules from the model, and returns affected rules.
346346func (model Model ) RemovePoliciesWithAffected (sec string , ptype string , rules [][]string ) ([][]string , error ) {
347- _ , err := model .GetAssertion (sec , ptype )
347+ assertion , err := model .GetAssertion (sec , ptype )
348348 if err != nil {
349349 return nil , err
350350 }
351+
351352 var affected [][]string
353+ removeSet := make (map [string ]struct {}, len (rules ))
354+
352355 for _ , rule := range rules {
353- index , ok := model [ sec ][ ptype ]. PolicyMap [ strings .Join (rule , DefaultSep )]
354- if ! ok {
356+ key := strings .Join (rule , DefaultSep )
357+ if _ , ok := assertion . PolicyMap [ key ]; ! ok {
355358 continue
356359 }
357-
360+ if _ , exists := removeSet [key ]; exists {
361+ continue
362+ }
363+ if affected == nil {
364+ affected = make ([][]string , 0 , len (rules ))
365+ }
358366 affected = append (affected , rule )
359- model [sec ][ptype ].Policy = append (model [sec ][ptype ].Policy [:index ], model [sec ][ptype ].Policy [index + 1 :]... )
360- delete (model [sec ][ptype ].PolicyMap , strings .Join (rule , DefaultSep ))
361- for i := index ; i < len (model [sec ][ptype ].Policy ); i ++ {
362- model [sec ][ptype ].PolicyMap [strings .Join (model [sec ][ptype ].Policy [i ], DefaultSep )] = i
367+ removeSet [key ] = struct {}{}
368+ }
369+
370+ if len (removeSet ) == 0 {
371+ return affected , nil
372+ }
373+
374+ compactPolicy := assertion .Policy [:0 ]
375+ compactPolicyMap := make (map [string ]int , len (assertion .Policy )- len (removeSet ))
376+ for _ , policyRule := range assertion .Policy {
377+ key := strings .Join (policyRule , DefaultSep )
378+ if _ , ok := removeSet [key ]; ok {
379+ continue
363380 }
381+ compactPolicyMap [key ] = len (compactPolicy )
382+ compactPolicy = append (compactPolicy , policyRule )
364383 }
384+
385+ assertion .Policy = compactPolicy
386+ assertion .PolicyMap = compactPolicyMap
387+
365388 return affected , nil
366389}
367390
0 commit comments