port gg-uid to nebkor-maelstrom

This commit is contained in:
Joe Ardent 2024-05-20 12:55:12 -07:00
parent 851e9a6711
commit 417f01d484
2 changed files with 26 additions and 30 deletions

View file

@ -6,7 +6,5 @@ authors.workspace = true
license-file.workspace = true
[dependencies]
async-trait.workspace = true
maelstrom-node.workspace = true
serde_json.workspace = true
tokio.workspace = true
nebkor-maelstrom = { path = "../nebkor-maelstrom" }

View file

@ -1,37 +1,35 @@
use async_trait::async_trait;
use maelstrom::protocol::Message;
use maelstrom::{done, protocol::MessageBody, Node, Result, Runtime};
use serde_json::{Map, Value};
use std::sync::Arc;
use std::{rc::Rc, sync::Mutex};
#[tokio::main]
async fn main() {
let handler = Arc::new(Handler);
let _ = Runtime::new()
.with_handler(handler)
.run()
.await
.unwrap_or_default();
use nebkor_maelstrom::{protocol::Payload, Body, Message, Node, Runner};
fn main() {
let out = std::io::stdout().lock();
let input = std::io::stdin().lock();
let node = GenUid;
let node = Rc::new(Mutex::new(node));
let runner = Runner::new(out, node);
runner.run(input);
}
#[derive(Clone, Default)]
struct Handler;
struct GenUid;
#[async_trait]
impl Node for Handler {
async fn process(&self, runtime: Runtime, req: Message) -> Result<()> {
let id = runtime.node_id();
let mid = runtime.next_msg_id();
if req.get_type() == "generate" {
let extra: Map<String, Value> = [("id".to_string(), format!("{id}{mid}").into())]
impl Node for GenUid {
fn handle(&mut self, runner: &Runner, msg: &Message) {
let id = runner.node_id();
let mid = runner.next_msg_id();
if msg.body.typ == "generate" {
let payload: Payload = [("id".to_string(), format!("{id}{mid}").into())]
.into_iter()
.collect();
let body = MessageBody::from_extra(extra)
.with_type("generate_ok")
.and_msg_id(mid);
return runtime.reply(req, body).await;
}
let body = Body::from_type("generate_ok")
.with_msg_id(mid)
.with_payload(payload);
done(runtime, req)
runner.reply(msg, body);
}
}
}