OpenAI speaks Rust, knows about crates
So there's all this hype about ChatGPT, the AI chatbot from OpenAI. People are using it to solve the advent of code puzzels. So I figured, how well does it do Rust? Can I just point it to a specification, tell it what to code, and would it be any good? Well..
I told it:
Write a function in Rust that parses a Vec<u8> containing a received RIPv2 packet, as described in RFC 2453, into a struct. use the "nom" crate for parsing. do not omit anything for brevity. Comment the code to explain how it's working. Do not write tests.
This was its reply:
use nom::{
number::complete::{be_u16, be_u32},
sequence::tuple,
IResult
};
// This struct represents a RIPv2 packet, as described in RFC 2453.
// It contains the command, version, and the list of routes.
#[derive(Debug)]
pub struct RipPacket {
command: u8,
version: u8,
routes: Vec<RipRoute>,
}
// This struct represents a single route in a RIPv2 packet.
// It contains the address family, route tag, IP address,
// subnet mask, next hop IP address, and metric.
#[derive(Debug)]
pub struct RipRoute {
address_family: u16,
route_tag: u16,
ip_address: u32,
subnet_mask: u32,
next_hop_ip_address: u32,
metric: u32,
}
// This function parses a Vec<u8> containing a received RIPv2 packet
// into a struct. It uses the nom crate for parsing.
pub fn parse_rip_packet(input: &[u8]) -> IResult<&[u8], RipPacket> {
let (input, (command, version)) = tuple((be_u8, be_u8))(input)?;
let (input, routes) = parse_routes(input)?;
let packet = RipPacket {
command,
version,
routes,
};
Ok((input, packet))
}
// This function parses a Vec<u8> containing a list of routes
// in a RIPv2 packet into a Vec<RipRoute>. It uses the nom crate
// for parsing.
fn parse_routes(input: &[u8]) -> IResult<&[u8], Vec<RipRoute>> {
let mut routes = Vec::new();
let mut input = input;
loop {
let (i, route) = parse_route(input)?;
routes.push(route);
input = i;
if i.is_empty() {
break;
}
}
Ok((input, routes))
}
// This function parses a Vec<u8> containing a single route
// in a RIPv2 packet into a RipRoute. It uses the nom crate
// for parsing.
fn parse_route(input: &[u8]) -> IResult<&[u8], RipRoute> {
let (input, (address_family, route_tag, ip_address, subnet_mask, next_hop_ip_address, metric)) =
tuple((be_u16, be_u16, be_u32, be_u32, be_u32, be_u32))(input)?;
let route = RipRoute {
address_family,
route_tag,
ip_address,
subnet_mask,
next_hop_ip_address,
metric,
};
Ok((input, route))
}
This almost compiles. For some reason it forgot to \use\\ be\_u8. But if you add that, it compiles. It also forgot to make the struct fields public, but I'm sure that if you ask it to do that it will.