C code defining "mileage" type - Representing miles and chain from a zero point, create a library to allow arithmetic operations between values of the type ( in strings as M:C) but use an appropriate internal form ...
Assistant
User
How would the code be different for C++ which lets as override operators directly so we can just use + - assuming the types are the same?
Assistant
User
Can we expand the l;ibrary to accomodate that in calculating actual railway distances, some milages are definied from a junction on another line etc?
Assistant
Certainly! Below is a simple C implementation of a "mileage" type, representing miles and chains from a zero point. It provides a library interface to parse and output the values as "M:C" strings (e.g., "12:15"), but internally stores them as an integer number of chains for easy arithmetic.
We'll assume the traditional railway measurement where 1 mile = 80 chains.
mileage.h
c
#ifndef MILEAGE_H
#define MILEAGE_H
#include <stdbool.h>
// Opaque mileage type
typedef struct Mileage Mileage;
// Create a mileage from string "M:C" (e.g., "12:15")
// Returns NULL if parsing fails
Mileage *mileage_from_string(const char *str);
// Convert mileage to string "M:C" format (stored in provided buffer)
// Buffer should be at least 16 bytes
void mileage_to_string(const Mileage *m, char *buffer, size_t size);
// Free Mileage object
void mileage_free(Mileage *m);
// Add two mileage values, return new Mileage
Mileage *mileage_add(const Mileage *a, const Mileage *b);
// Subtract b from a, return new Mileage
// Result can be negative, which we'll represent internally as signed chains
Mileage *mileage_subtract(const Mileage *a, const Mileage *b);
// Compare two mileage values
// Returns -1 if a < b, 0 if a == b, 1 if a > b
int mileage_compare(const Mileage *a, const Mileage *b);
// Create mileage from miles and chains values
// Returns NULL if input invalid (e.g., chains < 0 or >= 80)
Mileage *mileage_new(int miles, int chains);
#endif // MILEAGE_H
mileage.c
c
#include "mileage.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define CHAINS_PER_MILE 80
struct Mileage {
long long total_chains; // can be negative if needed
};
// Forward declarations of internal helpers
static bool parse_mileage_string(const char *str, int *miles, int *chains);
static void mileage_to_miles_chains(long long chains, int *miles, int *c);
Mileage *mileage_from_string(const char *str) {
int miles, chains;
if (!parse_mileage_string(str, &miles, &chains))
return NULL;
return mileage_new(miles, chains);
}
Mileage *mileage_new(int miles, int chains) {
if (chains < 0 || chains >= CHAINS_PER_MILE) {
return NULL; // invalid
}
Mileage *m = malloc(sizeof(Mileage));
if (!m) return NULL;
m->total_chains = (long long)miles * CHAINS_PER_MILE + chains;
return m;
}
void mileage_free(Mileage *m) {
if (m) free(m);
}
void mileage_to_string(const Mileage *m, char *buffer, size_t size) {
if (!m || !buffer || size < 16) {
if (buffer && size > 0) buffer[0] = '\0';
return;
}
int miles, chains;
mileage_to_miles_chains(m->total_chains, &miles, &chains);
snprintf(buffer, size, "%d:%d", miles, chains);
}
Mileage *mileage_add(const Mileage *a, const Mileage *b) {
if (!a || !b) return NULL;
Mileage *res = malloc(sizeof(Mileage));
if (!res) return NULL;
res->total_chains = a->total_chains + b->total_chains;
return res;
}
Mileage *mileage_subtract(const Mileage *a, const Mileage *b) {
if (!a || !b) return NULL;
Mileage *res = malloc(sizeof(Mileage));
if (!res) return NULL;
res->total_chains = a->total_chains - b->total_chains;
return res;
}
int mileage_compare(const Mileage *a, const Mileage *b) {
if (!a || !b) {
// handle NULL pointers as equal or error
return 0;
}
if (a->total_chains < b->total_chains) return -1;
if (a->total_chains > b->total_chains) return 1;
return 0;
}
// --- Internal helpers ---
// Parse "M:C" string, fill miles and chains
// Return true on success, false if invalid
static bool parse_mileage_string(const char *str, int *miles, int *chains) {
if (!str || !miles || !chains) return false;
// Find colon separator
const char *colon = strchr(str, ':');
if (!colon) return false;
// Parse miles (could be negative)
int len_miles = colon - str;
if (len_miles == 0) return false;
char miles_str[16];
if (len_miles >= (int)sizeof(miles_str)) return false;
strncpy(miles_str, str, len_miles);
miles_str[len_miles] = '\0';
// Parse miles int
char *endptr;
long m = strtol(miles_str, &endptr, 10);
if (*endptr != '\0') return false;
// Parse chains
const char *chains_str = colon + 1;
if (strlen(chains_str) == 0) return false;
long c = strtol(chains_str, &endptr, 10);
if (*endptr != '\0') return false;
if (c < 0 || c >= CHAINS_PER_MILE) return false;
*miles = (int)m;
*chains = (int)c;
return true;
}
// Convert total chains to miles and chains
// Properly handles negative values (e.g. -1 chain = -1:79)
static void mileage_to_miles_chains(long long chains, int *miles, int *c) {
// Note: For negative chains, we want representation as negative miles + positive chains
if (chains >= 0) {
*miles = (int)(chains / CHAINS_PER_MILE);
*c = (int)(chains % CHAINS_PER_MILE);
} else {
// Example: chains = -1
// miles = -1 + 1 = 0?
// We calculate like this:
// Integer division of negative numbers rounds towards zero in C99,
// but here we want floor division.
long long m = (chains + 1) / CHAINS_PER_MILE - 1;
long long rem = chains - m * CHAINS_PER_MILE;
*miles = (int)m;
*c = (int)rem;
}
}
Internally stores mileage as total chains (signed long long).
Allows negative mileage for difference calculations.
Provides string parsing and formatting helpers.
Includes basic arithmetic and comparison.
You can extend it with multiplication, division or more features as needed.
Great question! In C++, you can encapsulate the mileage logic in a class and overload operators like +, -, ==, <, etc. so that the code looks idiomatic and easy to use.
Here’s how the C code would transform into a C++ class, leveraging operator overloading and value semantics.
mileage.hpp (header)
cpp
#ifndef MILEAGE_HPP
#define MILEAGE_HPP
#include <string>
#include <stdexcept>
class Mileage {
private:
static constexpr int CHAINS_PER_MILE = 80;
// Internally store total chains relative to zero point
long long total_chains;
// Helper: convert miles and chains to total_chains
static long long to_chains(int miles, int chains);
// Helper: parse string "M:C"
static void parse_string(const std::string& str, int& miles, int& chains);
// Helper: convert total_chains to miles and chains (properly for negatives)
void to_miles_chains(int& miles, int& chains) const;
public:
Mileage() : total_chains(0) {}
Mileage(int miles, int chains);
// Constructs Mileage from string "M:C" like "12:15"
explicit Mileage(const std::string& str);
// Accessors
int miles() const;
int chains() const;
// Convert back to string "M:C"
std::string to_string() const;
// Operator overloads
Mileage operator+(const Mileage& rhs) const;
Mileage operator-(const Mileage& rhs) const;
Mileage& operator+=(const Mileage& rhs);
Mileage& operator-=(const Mileage& rhs);
bool operator==(const Mileage& rhs) const;
bool operator!=(const Mileage& rhs) const;
bool operator<(const Mileage& rhs) const;
bool operator<=(const Mileage& rhs) const;
bool operator>(const Mileage& rhs) const;
bool operator>=(const Mileage& rhs) const;
};
#endif // MILEAGE_HPP
Encapsulated the internal total_chains inside a class.
Exception-based error handling (invalid_argument) on invalid input.
Constructors handle string or miles/chains input.
Operator overloading for +, -, comparison, and compound assignments (+=, -=).
Methods to convert to/from string.
No manual memory management; all automatic.
This makes usage straightforward & idiomatic in C++. Instead of calling functions like mileage_add(a, b), you just write a + b!
If you'd like, I can help you generate a complete example project or add more operators (e.g., multiplication by scalar).
Absolutely! In real railway systems, mileages are often measured relative to multiple zero points (origins), e.g. kilometers or miles along different lines or junctions. Modeling this accurately requires extending the Mileage type to reference the "base point" it's measured from.
High-level design for multiple references ("origins")
Introduce a type BasePoint (or LineReference) that identifies the reference zero point (junction, line start, or section zero).
Mileage values are then represented relative to a BasePoint.
Arithmetic operations like addition and subtraction only make sense between mileages sharing the same BasePoint.
Support conversion between BasePoints by defining distances between BasePoints (offsets).
Support chained references, if necessary (e.g., BasePoint A references BasePoint B with an offset).
Extending the C++ class design
To accommodate this:
Define a BasePoint class or at least an identifier for each base point.
In the Mileage class, add a BasePoint member as the reference.
Arithmetic operators will either restrict operations to matching BasePoints or allow explicit conversions.
Optionally maintain a map of offsets/distances between BasePoints to support conversion.
Step 2 — Extend Mileage to include BasePoint reference
cpp
#include "basepoint.hpp"
#include <string>
#include <stdexcept>
class Mileage {
private:
static constexpr int CHAINS_PER_MILE = 80;
long long total_chains;
BasePoint base_point;
public:
Mileage(const BasePoint& base, int miles, int chains);
explicit Mileage(const BasePoint& base, const std::string& str);
// Access members
BasePoint get_base_point() const { return base_point; }
// Arithmetic operators require matching base points
Mileage operator+(const Mileage& rhs) const;
Mileage operator-(const Mileage& rhs) const;
// Add compound assignment operators similarly
std::string to_string() const;
// Other members as before...
};
Step 3 — Implement arithmetic with base point checks
cpp
Mileage Mileage::operator+(const Mileage& rhs) const {
if (base_point != rhs.base_point) {
throw std::invalid_argument("Cannot add mileages from different base points");
}
return Mileage(base_point, 0, 0).with_total_chains(this->total_chains + rhs.total_chains);
}
// Provide a private or protected helper for direct total_chains construction:
Mileage& Mileage::with_total_chains(long long chains) {
this->total_chains = chains;
return *this;
}
Similarly for operator-.
Step 4 — Support offsets between BasePoints
You could maintain a global registry of BasePoints and offsets:
cpp
#include <unordered_map>
class BasePointRegistry {
private:
// Map of base_point pairs to offset in chains: offset = basepoint2 - basepoint1 in chains
std::unordered_map<std::pair<BasePoint, BasePoint>, long long, PairHash> offsets;
public:
// Register offset from base1 to base2 in chains
void add_offset(const BasePoint& base1, const BasePoint& base2, long long offset_in_chains);
// Get offset from base1 to base2, if known; throws if unknown
long long get_offset(const BasePoint& base1, const BasePoint& base2) const;
// Converts Mileage from one base point to another using offsets
Mileage convert_base(const Mileage& m, const BasePoint& new_base) const;
};
The conversion method would:
Query offset between base points.
Add/subtract offset from mileage's total_chains.
Return Mileage with new base point.
Usage example:
cpp
BasePoint bpA("LineA_JunctionX");
BasePoint bpB("LineB_Start");
Mileage m1(bpA, "12:15");
Mileage m2(bpB, "3:50");
BasePointRegistry registry;
registry.add_offset(bpA, bpB, 1234); // offset in chains between base points (LineB is 1234 chains ahead of LineA)
Mileage m1_in_bpB = registry.convert_base(m1, bpB);
Mileage sum = m1_in_bpB + m2; // now both relative to same base point => legal operation
std::cout << "Sum mileage: " << sum.to_string() << " relative to " << bpB.get_id() << '\n';
Summary of the more general mileage design with base points:
Feature
Description
BasePoint
Identifies zero reference (e.g., junction, line start)
Mileage stores BasePoint
Mileage is always relative to a base
Arithmetic requires matching bases
Add/subtract only allowed between same base
Registry of base offsets
Convert mileage between different bases
Negative and positive mileages
Supported as before
This expanded model accurately mirrors how mileages in railways work in real life, where you have several zero points and relative measurements.
If you'd like, I can provide a full working code example with all this, or show how to integrate with the previous classes! Just ask!
Not yet included in a published release.
#include "mileage.hpp"
#include <sstream>
#include <cstdlib>
using std::string;
using std::invalid_argument;
long long Mileage::to_chains(int miles, int chains) {
if (chains < 0 || chains >= CHAINS_PER_MILE) {
throw invalid_argument("Chains must be between 0 and 79");
}
return static_cast<long long>(miles) * CHAINS_PER_MILE + chains;
}
void Mileage::parse_string(const string& str, int& miles, int& chains) {
auto colon_pos = str.find(':');
if (colon_pos == string::npos) {
throw invalid_argument("Invalid format, missing colon");
}
string miles_part = str.substr(0, colon_pos);
string chains_part = str.substr(colon_pos + 1);
if (miles_part.empty() || chains_part.empty()) {
throw invalid_argument("Invalid format, empty miles or chains");
}
// Parse miles
char* endptr = nullptr;
long m = std::strtol(miles_part.c_str(), &endptr, 10);
if (*endptr != '\0') {
throw invalid_argument("Invalid miles part");
}
long c = std::strtol(chains_part.c_str(), &endptr, 10);
if (*endptr != '\0') {
throw invalid_argument("Invalid chains part");
}
if (c < 0 || c >= CHAINS_PER_MILE) {
throw invalid_argument("Chains out of range");
}
miles = static_cast<int>(m);
chains = static_cast<int>(c);
}
void Mileage::to_miles_chains(int& miles_out, int& chains_out) const {
long long c = total_chains;
if (c >= 0) {
miles_out = static_cast<int>(c / CHAINS_PER_MILE);
chains_out = static_cast<int>(c % CHAINS_PER_MILE);
} else {
// floor division for negative numbers
long long m = (c + 1) / CHAINS_PER_MILE - 1;
long long rem = c - m * CHAINS_PER_MILE;
miles_out = static_cast<int>(m);
chains_out = static_cast<int>(rem);
}
}
// -- Public API --
Mileage::Mileage(int miles, int chains)
: total_chains(to_chains(miles, chains)) {}
Mileage::Mileage(const string& str) {
int miles, chains;
parse_string(str, miles, chains);
total_chains = to_chains(miles, chains);
}
int Mileage::miles() const {
int m, c;
to_miles_chains(m, c);
return m;
}
int Mileage::chains() const {
int m, c;
to_miles_chains(m, c);
return c;
}
string Mileage::to_string() const {
int m, c;
to_miles_chains(m, c);
std::ostringstream oss;
oss << m << ':' << c;
return oss.str();
}
// Operators
Mileage Mileage::operator+(const Mileage& rhs) const {
return Mileage(0, 0).operator=(Mileage(0, 0)); // dummy initialization fix below
// Replace this dummy with actual operator+ code below:
}
Mileage Mileage::operator-(const Mileage& rhs) const {
return Mileage(0, 0); // dummy, see below
}
Mileage& Mileage::operator+=(const Mileage& rhs) {
total_chains += rhs.total_chains;
return *this;
}
Mileage& Mileage::operator-=(const Mileage& rhs) {
total_chains -= rhs.total_chains;
return *this;
}
bool Mileage::operator==(const Mileage& rhs) const {
return total_chains == rhs.total_chains;
}
bool Mileage::operator!=(const Mileage& rhs) const {
return !(*this == rhs);
}
bool Mileage::operator<(const Mileage& rhs) const {
return total_chains < rhs.total_chains;
}
bool Mileage::operator<=(const Mileage& rhs) const {
return total_chains <= rhs.total_chains;
}
bool Mileage::operator>(const Mileage& rhs) const {
return total_chains > rhs.total_chains;
}
bool Mileage::operator>=(const Mileage& rhs) const {
return total_chains >= rhs.total_chains;
}
// Fix operator+ and operator- properly
Mileage Mileage::operator+(const Mileage& rhs) const {
Mileage result(0, 0);
result.total_chains = this->total_chains + rhs.total_chains;
return result;
}
Mileage Mileage::operator-(const Mileage& rhs) const {
Mileage result(0, 0);
result.total_chains = this->total_chains - rhs.total_chains;
return result;
}