Last active: a year ago
thread_channel.rs
use std::sync::mpsc;
use std::thread;
fn main() {
let cores = num_cpus::get();
let (tx, rx) = mpsc::channel();
(0..cores).for_each(|core| {
let tx = tx.clone();
thread::spawn(move || {
if let Err(e) = tx.send(core) {
println!("Get error: {e}")
}
});
});
drop(tx);
for received in rx {
println!("Get value from thread: {received}")
Last active: 2 years ago
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> Self {
Self(x)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn main() {
let n = MyBox::new(40);
Last active: 2 years ago
use ::anyhow::Result;
fn main() -> Result<()> {
let mut arr = [1, 2, 3];
println!("{:?}", arr);
let p1 = arr.as_mut_ptr();
let p1_size = p1 as usize;
let p2 = (p1_size + 4) as *mut i32;
println!("{:?}", p2);
unsafe {
*p2 += 40;
}
println!("{:?}", arr);
Ok(())
}
Last active: 2 years ago
struct Count {
pub value: u32,
inter_value: u32,
}
impl Count {
fn new(value: u32) -> Self {
Self {
value,
inter_value: 0,
}
}
}
impl Iterator for Count {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.inter_value < self.value {
self.inter_value += 1;
Last active: 2 years ago
use std::fmt::{Debug, Formatter};
struct Cache<T, E>
where
T: Fn(E) -> E,
E: Clone + Debug,
{
query: T,
value: Option<E>,
}
impl<T, E> Cache<T, E>
where
T: Fn(E) -> E,
E: Clone + Debug,
{
fn new(query: T) -> Self {
Self { query, value: None }
}
Last active: 2 years ago
const template = document.querySelector<HTMLTemplateElement>('#template')!;
const temp = template.content;
const app = document.querySelector('#app')!;
app.append(temp);
const fragment = document.createDocumentFragment();
const colors = ['red', 'green', 'blue'];
colors.forEach((color) => {
const shadowHost = document.createElement('div');
const shadow = shadowHost.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<p>Make me ${color}</p>
<style>
p {
color: ${color}
}
</style>
`;
Last active: 2 years ago
Box lifetime bounds for dyn trait
use crate::post::{Post, Summary, Tweet, Weibo};
mod post;
fn create_one<'a>(
switch: bool,
username: &'a str,
title: String,
content: String,
) -> Box<dyn Summary + 'a> {
let post = Post::new(title, username, content);
if switch {
Box::new(Weibo::new(username, post))
} else {
Box::new(Tweet::new(username, post))
}
}
fn main() {
let username = "xfy";
Last active: 2 years ago
Box lifetime bounds for dyn trait
pub struct Weibo<'a> {
username: &'a str,
post: Post<'a>,
}
impl<'a> Weibo<'a> {
pub fn new(username: &'a str, post: Post<'a>) -> Self {
Self { username, post }
}
}
pub struct Tweet<'a> {
username: &'a str,
post: Post<'a>,
}
impl<'a> Tweet<'a> {
pub fn new(username: &'a str, post: Post<'a>) -> Self {
Self { username, post }
}
Last active: 2 years ago
use std::slice::from_raw_parts;
use std::str::from_utf8_unchecked;
fn main() {
let (p, len) = get_memory_str();
let msg = read_memory_location(p, len);
println!("The {} bytes at {:?} stored: {}", len, p, msg)
}
fn get_memory_str() -> (*const u8, usize) {
// let str = "Hello world!";
let str = "Hello world!".to_string();
(str.as_ptr(), str.len())
}
fn read_memory_location(p: *const u8, len: usize) -> &'static str {
unsafe { from_utf8_unchecked(from_raw_parts(p, len)) }
}
Last active: 2 years ago
use anyhow::Result;
use std::io::{stdin, BufRead};
use std::slice::from_raw_parts;
use std::str::from_utf8_unchecked;
fn main() -> Result<()> {
let (p, len) = read_user_input()?;
let msg = read_memory((p, len));
println!("The {} bytes at {:?} stored: {}", len, p, msg);
Ok(())
}
type MyPoint = (*const u8, usize);
fn read_user_input() -> Result<MyPoint> {
let mut user_input = String::new();
let stdin = stdin();
stdin.lock().read_line(&mut user_input)?;
Ok(get_memory_location(&user_input))
}
Last active: 2 years ago
fn main() {
let mut values = [1, 2];
let p1 = values.as_mut_ptr();
let first_address = p1 as usize;
// println!("{}", std::mem::size_of::<i32>());
let second_address = first_address + 4;
let p2 = second_address as *mut i32;
unsafe {
*p2 += 1;
}
println!("{:?}", values)
}
Last active: 2 years ago
interface Draw {
draw(): void;
}
class Size {
constructor(public width: number, public height: number) {}
}
class Button implements Draw {
size: Size;
constructor(width: number, height: number, public label: string) {
this.size = new Size(width, height);
}
draw() {
console.log(
`Drawing button width: ${this.size.width} height: ${this.size.height} with label: ${this.label}`
);
}
Last active: 2 years ago
trait Draw {
fn draw(&self) {}
}
struct Size {
pub width: u32,
pub height: u32,
}
struct Button {
pub label: String,
pub size: Size,
}
impl Draw for Button {
fn draw(&self) {
println!(
"Drawing button width: {} and height: {} with label: {}",
self.size.width, self.size.height, self.label
);
}