[PATCH] rust: net: add OOT sample modules.
From: Michele Dalle Rive
Date: Thu Aug 17 2023 - 09:51:47 EST
Add two sample modules that showcase some functionalities of the Rust
socket API.
Signed-off-by: Michele Dalle Rive <dallerivemichele@xxxxxxxxx>
---
samples/rust/rust_socket.rs | 45 +++++++++++++++++++++++++++++++++
samples/rust/rust_tcp_server.rs | 34 +++++++++++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 samples/rust/rust_socket.rs
create mode 100644 samples/rust/rust_tcp_server.rs
diff --git a/samples/rust/rust_socket.rs b/samples/rust/rust_socket.rs
new file mode 100644
index 000000000000..fc1ed8536e57
--- /dev/null
+++ b/samples/rust/rust_socket.rs
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust minimal sample.
+
+use core::str::FromStr;
+use kernel::prelude::*;
+use kernel::net::socket::*;
+use kernel::net::ip::IpProtocol;
+use kernel::net::addr::{SocketAddr};
+use kernel::net::AddressFamily;
+use kernel::flag_set;
+
+module! {
+ type: RustSocket,
+ name: "rust_socket",
+ author: "Rust for Linux Contributors",
+ description: "Rust sockets support sample",
+ license: "GPL",
+}
+
+struct RustSocket {}
+
+impl kernel::Module for RustSocket {
+ fn init(_module: &'static ThisModule) -> Result<Self> {
+ let sock = Socket::new(AddressFamily::Inet,
SockType::Datagram, IpProtocol::Udp)?;
+ let addr = "0.0.0.0:8000";
+ sock.bind(SocketAddr::from_str(addr)?)?;
+
+ sock.set_option::<opts::sock::ReuseAddr>(true)?;
+
+ assert_eq!(sock.sockname()?, SocketAddr::from_str(addr)?);
+
+ let mut buf = [0; 1024];
+ while let Ok((bytes, msghdr)) = sock.receive_msg(&mut buf,
flag_set!()) {
+ if bytes == 0 {
+ break;
+ }
+ pr_info!("Received {} bytes from {}", bytes,
msghdr.address().unwrap());
+ if msghdr.flags().contains(flags::MessageFlag::Trunc) {
+ pr_info!("The message was truncated");
+ }
+ }
+ Ok(Self{})
+ }
+}
\ No newline at end of file
diff --git a/samples/rust/rust_tcp_server.rs b/samples/rust/rust_tcp_server.rs
new file mode 100644
index 000000000000..987c4c752d2b
--- /dev/null
+++ b/samples/rust/rust_tcp_server.rs
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Rust echo server sample.
+
+use core::str::FromStr;
+use kernel::prelude::*;
+use kernel::net::tcp::TcpListener;
+use kernel::net::addr::SocketAddr;
+use kernel::flag_set;
+
+module! {
+ type: RustTcpServer,
+ name: "rust_tcp_server",
+ author: "Rust for Linux Contributors",
+ license: "GPL",
+}
+
+struct RustTcpServer {}
+
+impl kernel::Module for RustTcpServer {
+ fn init(_module: &'static ThisModule) -> Result<Self> {
+ let listener =
TcpListener::new(SocketAddr::from_str("0.0.0.0:8000")?)?;
+ while let Ok(stream) = listener.accept() {
+ let mut buf = [0; 1024];
+ while let Ok(size) = stream.receive(&mut buf, flag_set!()) {
+ if size == 0 {
+ break;
+ }
+ stream.send(&buf[..size], flag_set!())?;
+ }
+ }
+ Ok(Self {})
+ }
+}
--
2.41.0