我正在尝试实现一个基本上包裹u32
的IP地址类型:
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Address(u32);
我实施了对IP地址有意义的std::ops
运营商(&
,|
,+
,-
等。 )。唯一导致问题的是std::ops::Index
:
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Address(u32);
enum Byte {
A,
B,
C,
D
}
impl ops::Index<Byte> for Address {
type Output = u8;
fn index<'a>(&'a self, byte: Byte) -> &'a Self::Output {
match byte {
Byte::A => ((self.0 & 0xFF000000) >> 24) as u8,
Byte::B => ((self.0 & 0x00FF0000) >> 16) as u8,
Byte::C => ((self.0 & 0x0000FF00) >> 8) as u8,
Byte::D => (self.0 & 0x000000FF) as u8,
}
}
}
这显然无法编译,因为在预期u8
时我无法返回&u8
。天真的解决方法是:
impl ops::Index<Byte> for Address {
type Output = u8;
fn index<'a>(&'a self, byte: Byte) -> &'a Self::Output {
match byte {
Byte::A => &(((self.0 & 0xFF000000) >> 24) as u8),
Byte::B => &(((self.0 & 0x00FF0000) >> 16) as u8),
Byte::C => &(((self.0 & 0x0000FF00) >> 8) as u8),
Byte::D => &((self.0 & 0x000000FF) as u8),
}
}
}
但是,当然,一旦函数返回,我就不能再返回对不存在的值的引用。
在这种情况下我有办法实现std::ops::Index
吗?对我来说似乎不是这样,但我希望有人可以证明我错了。
答案 0 :(得分:6)
嗯,解决这个问题的最简单和最惯用的方法是不实现Index
,而只是使用名为octet
的方法。 Index
用于索引容器;它根本不兼容即时生成新值。
因此。你有答案。
你绝对不应该 做关于的任何事情来描述,因为没有充分的理由去做,我只是在写作它是因为你技术上询问是否有任何方式......
你已被警告过了。
......八位字节就在那里!除非您为具有不是 8位的字节的机器进行编译,或者具有比8位更精细的寻址,否则您没有理由不这样做这样做:
use std::ops;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Address(u32);
enum Byte {
A,
B,
C,
D
}
impl ops::Index<Byte> for Address {
type Output = u8;
#[cfg(target_endian="big")]
fn index<'a>(&'a self, byte: Byte) -> &'a u8 {
use std::mem;
let bytes = unsafe { mem::transmute::<_, &[u8; 4]>(&self.0) };
match byte {
Byte::A => &bytes[0],
Byte::B => &bytes[1],
Byte::C => &bytes[2],
Byte::D => &bytes[3],
}
}
#[cfg(target_endian="little")]
fn index<'a>(&'a self, byte: Byte) -> &'a u8 {
use std::mem;
let bytes = unsafe { mem::transmute::<_, &[u8; 4]>(&self.0) };
match byte {
Byte::A => &bytes[3],
Byte::B => &bytes[2],
Byte::C => &bytes[1],
Byte::D => &bytes[0],
}
}
}
fn main() {
assert_eq!(Address(0x12345678)[Byte::A], 0x12);
}
我的意思是,除了这是为了混淆语法而不必要地使用unsafe
;索引地址与索引整数一样有意义:非常少。