@@ -1018,20 +1018,27 @@ impl PyStr {
1018
1018
}
1019
1019
1020
1020
#[ pymethod]
1021
- fn replace ( & self , old : PyStrRef , new : PyStrRef , count : OptionalArg < isize > ) -> Wtf8Buf {
1021
+ fn replace ( & self , args : ReplaceArgs ) -> Wtf8Buf {
1022
+ use std:: cmp:: Ordering ;
1023
+
1022
1024
let s = self . as_wtf8 ( ) ;
1023
- match count {
1024
- OptionalArg :: Present ( max_count) if max_count >= 0 => {
1025
- if max_count == 0 || ( s. is_empty ( ) && !old. is_empty ( ) ) {
1026
- // nothing to do; return the original bytes
1025
+ let ReplaceArgs { old, new, count } = args;
1026
+
1027
+ match count. cmp ( & 0 ) {
1028
+ Ordering :: Less => s. replace ( old. as_wtf8 ( ) , new. as_wtf8 ( ) ) ,
1029
+ Ordering :: Equal => s. to_owned ( ) ,
1030
+ Ordering :: Greater => {
1031
+ let s_is_empty = s. is_empty ( ) ;
1032
+ let old_is_empty = old. is_empty ( ) ;
1033
+
1034
+ if s_is_empty && !old_is_empty {
1027
1035
s. to_owned ( )
1028
- } else if s . is_empty ( ) && old . is_empty ( ) {
1036
+ } else if s_is_empty && old_is_empty {
1029
1037
new. as_wtf8 ( ) . to_owned ( )
1030
1038
} else {
1031
- s. replacen ( old. as_wtf8 ( ) , new. as_wtf8 ( ) , max_count as usize )
1039
+ s. replacen ( old. as_wtf8 ( ) , new. as_wtf8 ( ) , count as usize )
1032
1040
}
1033
1041
}
1034
- _ => s. replace ( old. as_wtf8 ( ) , new. as_wtf8 ( ) ) ,
1035
1042
}
1036
1043
}
1037
1044
@@ -1685,6 +1692,18 @@ impl FindArgs {
1685
1692
}
1686
1693
}
1687
1694
1695
+ #[ derive( FromArgs ) ]
1696
+ struct ReplaceArgs {
1697
+ #[ pyarg( positional) ]
1698
+ old : PyStrRef ,
1699
+
1700
+ #[ pyarg( positional) ]
1701
+ new : PyStrRef ,
1702
+
1703
+ #[ pyarg( any, default = -1 ) ]
1704
+ count : isize ,
1705
+ }
1706
+
1688
1707
pub fn init ( ctx : & Context ) {
1689
1708
PyStr :: extend_class ( ctx, ctx. types . str_type ) ;
1690
1709
0 commit comments