MCPcopy Index your code
hub / github.com/RustPython/RustPython / replace

Method replace

crates/vm/src/bytes_inner.rs:871–921  ·  view source on GitHub ↗
(
        &self,
        from: Self,
        to: Self,
        max_count: OptionalArg<isize>,
        vm: &VirtualMachine,
    )

Source from the content-addressed store, hash-verified

869 }
870
871 pub fn replace(
872 &self,
873 from: Self,
874 to: Self,
875 max_count: OptionalArg<isize>,
876 vm: &VirtualMachine,
877 ) -> PyResult<Vec<u8>> {
878 // stringlib_replace in CPython
879 let max_count = match max_count {
880 OptionalArg::Present(max_count) if max_count >= 0 => {
881 if max_count == 0 || (self.elements.is_empty() && !from.is_empty()) {
882 // nothing to do; return the original bytes
883 return Ok(self.elements.clone());
884 } else if self.elements.is_empty() && from.is_empty() {
885 return Ok(to.elements);
886 }
887 Some(max_count as usize)
888 }
889 _ => None,
890 };
891
892 // Handle zero-length special cases
893 if from.elements.is_empty() {
894 if to.elements.is_empty() {
895 // nothing to do; return the original bytes
896 return Ok(self.elements.clone());
897 }
898 // insert the 'to' bytes everywhere.
899 // >>> b"Python".replace(b"", b".")
900 // b'.P.y.t.h.o.n.'
901 return Ok(self.replace_interleave(to, max_count));
902 }
903
904 // Except for b"".replace(b"", b"A") == b"A" there is no way beyond this
905 // point for an empty self bytes to generate a non-empty bytes
906 // Special case so the remaining code always gets a non-empty bytes
907 if self.elements.is_empty() {
908 return Ok(self.elements.clone());
909 }
910
911 if to.elements.is_empty() {
912 // delete all occurrences of 'from' bytes
913 Ok(self.replace_delete(from, max_count))
914 } else if from.len() == to.len() {
915 // Handle special case where both bytes have the same length
916 Ok(self.replace_in_place(from, to, max_count))
917 } else {
918 // Otherwise use the more generic algorithms
919 self.replace_general(from, to, max_count, vm)
920 }
921 }
922
923 pub fn title(&self) -> Vec<u8> {
924 let mut res = vec![];

Callers 8

_path_isabsFunction · 0.45
_write_atomicFunction · 0.45
_resolve_filenameMethod · 0.45
filenameMethod · 0.45
filename2Method · 0.45
winerrorMethod · 0.45
trigger_signalsFunction · 0.45

Calls 8

replace_interleaveMethod · 0.80
replace_deleteMethod · 0.80
replace_in_placeMethod · 0.80
replace_generalMethod · 0.80
SomeClass · 0.50
is_emptyMethod · 0.45
cloneMethod · 0.45
lenMethod · 0.45

Tested by

no test coverage detected