add bytes/byterray title

This commit is contained in:
jgirardet
2019-05-06 21:37:15 +02:00
parent abf0a329ee
commit dc18356947
5 changed files with 51 additions and 5 deletions

View File

@@ -364,6 +364,7 @@ impl PyByteArrayRef {
.push(x.as_bigint().byte_or(vm)?);
Ok(())
}
#[pymethod(name = "pop")]
fn pop(self, vm: &VirtualMachine) -> PyResult<u8> {
let bytes = &mut self.inner.borrow_mut().elements;
@@ -371,6 +372,11 @@ impl PyByteArrayRef {
.pop()
.ok_or_else(|| vm.new_index_error("pop from empty bytearray".to_string()))
}
#[pymethod(name = "title")]
fn title(self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bytearray(self.inner.borrow().title()))
}
}
// fn set_value(obj: &PyObjectRef, value: Vec<u8>) {

View File

@@ -975,6 +975,30 @@ impl PyByteInner {
Ok(res)
}
pub fn title(&self) -> Vec<u8> {
let mut res = vec![];
let mut spaced = true;
for i in self.elements.iter() {
match i {
65..=90 | 97..=122 => {
if spaced {
res.push(i.to_ascii_uppercase());
spaced = false
} else {
res.push(i.to_ascii_lowercase());
}
}
_ => {
res.push(*i);
spaced = true
}
}
}
res
}
}
pub fn try_as_byte(obj: &PyObjectRef) -> Option<Vec<u8>> {

View File

@@ -402,6 +402,11 @@ impl PyBytesRef {
) -> PyResult {
Ok(vm.ctx.new_bytes(self.inner.replace(old, new, count)?))
}
#[pymethod(name = "title")]
fn title(self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bytes(self.inner.title()))
}
}
#[pyclass]