这是我的代码。
foo()很简单。它将参数与一些字符串一一比较。
main()有点复杂。它只是foo()用不同的字符串调用并计时,3 次。
#include <string.h>
#include <time.h>
#include <stdio.h>
int foo(const char *s)
{
int r = 0;
if (strcmp(s, "a11111111") == 0) {
r = 1;
} else if (strcmp(s, "b11111111") == 0) {
r = 2;
} else if (strcmp(s, "c11111111") == 0) {
r = 3;
} else if (strcmp(s, "d11111111") == 0) {
r = 4;
} else if (strcmp(s, "e11111111") == 0) {
r = 5;
} else if (strcmp(s, …Run Code Online (Sandbox Code Playgroud) 我想实现From枚举的特征。对于 可以usize,但对于函数类型则失败。
usize 和 function 类型有什么区别吗?
代码:
type Foo = fn (usize) -> usize;
enum Value {
Number(usize),
Function(Foo),
}
impl From<usize> for Value {
fn from(n: usize) -> Self {
Value::Number(n)
}
}
impl From<Foo> for Value {
fn from(f: Foo) -> Self {
Value::Function(f)
}
}
fn main() {
let n: usize = 123;
let vn: Value = n.into(); // OK for usize
fn testf(n: usize) -> usize { n * n }
let …Run Code Online (Sandbox Code Playgroud) 我手动定义一个结构并为其MyData实现PartialEq和特征。Hash
我定义了一个枚举,其中包括Rc<MyData>和Rc<RefCell<MyData>>。
我想要为枚举导出PartialEqand ,但失败了:Hash
PartialEq都Hash适用于Rc<MyData>;PartialEq于Rc<RefCell<MyData>>;Hash不起作用Rc<RefCell<MyData>>!我有两个问题:
为什么?为什么只有Hash不起作用Rc<RefCell<MyData>>?
如何修复它?
我无法Hash实施Rc<RefCell<MyData>>. 经过搜索后,我找到了一种方法:定义一个新的包装结构,例如struct RRWrapper<T> (Rc<RefCell<T>>),然后实现Hashthis RRWrapper。但这会带来很多代码。有惯用的方法吗?我认为这是一般用法。
预先感谢,
吴
Rc<RefCell<MyData>>PS:在我程序的实际代码中,只有枚举中有,但没有Rc<MyData>。我放在Rc<MyData>这里只是为了比较。Rc<RefCell<T>>PS2:在我的程序的实际代码中,枚举中有多个。
原始源代码:
use std::rc::Rc;
use std::cell::RefCell;
use std::hash::{Hash, Hasher};
struct MyData {
i: i64,
}
impl Hash …Run Code Online (Sandbox Code Playgroud) 我在GCC 4.8.2中遇到了一个奇怪的优化 - -O2,它删除了一个函数.
请参阅以下代码.
increase()和increase2()相同,只是后者有一个printf().
但是,如果在GCC中使用-O2,则会删除increase().
#include <stdio.h>
#include <stdint.h>
#include <arpa/inet.h>
void swap(uint64_t *vector)
{
uint32_t *p = (uint32_t *)vector;
uint32_t tmp = p[0];
p[0] = htonl(p[1]);
p[1] = htonl(tmp);
}
void increase(uint64_t *vector)
{
swap(vector);
(*vector)++;
swap(vector);
}
void increase2(uint64_t *vector)
{
swap(vector);
(*vector)++;
printf("touch...\n");
swap(vector);
}
int main()
{
uint64_t vector = 0xa;
increase(&vector);
printf("%lx\n", vector);
increase2(&vector);
printf("%lx\n", vector);
return 1;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
a
touch...
10000000000000a
Run Code Online (Sandbox Code Playgroud)
为什么?
提前致谢
对不起,我没说清楚.
问题不在于"删除功能",而是"功能不会影响参数".
Matt McNabb指出了原因,即严格的混叠规则.非常感谢你.
我__int128用作struct的成员.它可以找到-O0(没有优化).
但是,如果启用了优化(-O1),则会因段故障而崩溃.
它在指令处崩溃movdqa,需要将var对齐16,而地址的分配malloc()仅由8对齐.
我尝试禁用SSE优化-mno-sse,但无法编译:
/usr/include/x86_64-linux-gnu/bits/stdlib-float.h:27:1: error: SSE register return with SSE disabled
Run Code Online (Sandbox Code Playgroud)
所以,我能做些什么,如果我想使用__int128和-O1两者兼而有之?
在此先感谢吴
顺便说一下,如果__int128仅在堆栈上使用(不在堆上),似乎没问题.
====编辑====
对不起,我没说实话.
其实我没用过malloc().我使用了一个内存池lib,它返回8对齐的地址.我说malloc()只是为了让事情变得简单.
经过测试,我已经知道它malloc()与16对齐.并且__int128成员也在结构中对齐16.
所以问题是我的内存池lib.
非常感谢.