Add htons, ntohl, and ntohs to socket.rs#1664
Add htons, ntohl, and ntohs to socket.rs#1664coolreader18 merged 4 commits intoRustPython:masterfrom
Conversation
bc6ae61 to
2912d79
Compare
vm/src/stdlib/socket.rs
Outdated
| Ok(vm.new_int(host.to_be())) | ||
| } | ||
|
|
||
| fn socket_htons(host: u16, vm: &VirtualMachine) -> PyResult { |
There was a problem hiding this comment.
if the only difference is type, probably generic function will work
fn socket_hton<U>(host: U, _vm: &VirtualMachine) -> U {
host.to_be()
}and make rustfunc like this:
"htons" => ctx.new_rustfunc(socket_hton::<u16>),There was a problem hiding this comment.
I think you'd have to give the trait bound U: num_traits::PrimInt for that to work.
vm/src/stdlib/socket.rs
Outdated
| fn socket_ntohs(network: u16, vm: &VirtualMachine) -> PyResult { | ||
| if cfg!(target_endian = "big") { | ||
| Ok(vm.new_int(network)) | ||
| } |
There was a problem hiding this comment.
These seem like no-ops -- if the machine is big endian, leave it as is, or else if it's little endian, convert to little endian, i.e. leave it as is. You might be looking for u{16,32}::from_{le,be}
There was a problem hiding this comment.
Ah. Yeah, I couldn't find those before.
vm/src/stdlib/socket.rs
Outdated
| Ok(vm.new_int(host.to_be())) | ||
| } | ||
|
|
||
| fn socket_htons(host: u16, vm: &VirtualMachine) -> PyResult { |
There was a problem hiding this comment.
You can have all these functions just return u16 or u32 rather than a PyResult -- ctx.new_rustfunc takes care of converting the return type.
… ntoh with generics, simplified their return values, replaced a chunk of code with from_be.)
|
One sec, I might have pushed that a bit early. |
|
Let me know if you want those rebased. |
|
I think it's fine; thanks for contributing! I'll merge this once the ci finishes. |
|
It looks like the rustfmt job failed @metaphorshear, could you run |
For #1176. Just added each of those functions to
vm/src/stdlib/socket.rs, mostly by cheating off of thehtonlimplementation.