Rust Ownership, IDs and ECS Design¶
Rust ownership decides who controls a value's lifetime; an entity ID identifies a value that may already have been deleted. ECS changes how data and processing are organised. These are separate choices, so start with the requirement rather than replacing a C++ object hierarchy with an ECS by default.
Requirements: ownership first, persistent identity when needed¶
A world owns up to two bodies. Every live body has a position and may have a velocity; absent velocity differs from a present velocity of zero. One movement step adds velocity to position only when both components exist. The integer arithmetic in these bounded fixtures fits the signed position type; unbounded input needs an explicit overflow policy.
Start with plain records and a loop. Add IDs only when a selection must survive between operations, reject deleted bodies and refuse handles from another world. Add generations only when the requirement explicitly allows reusing a storage slot. A handle copy must not keep the body alive. At the last generation, retire the slot instead of wrapping; when no usable slot remains, insertion fails.
The existing C++ ECS course starts with records and non-reused IDs. Its generations extension adds slot reuse only for that changed requirement. This lesson deliberately exercises reuse with an 8-bit generation so retirement can be tested, not because every application needs a generational allocator.
C++: one owner, scoped handles and component stores¶
Save as design.cpp. The reference record loop and component world implement the same movement rule. All component mutation goes through the owning world; external callers cannot independently leave a velocity attached to a deleted slot.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
Both complete examples produce:
The shared pointer retains only an identity marker. It does not own a position or velocity. A copied handle therefore cannot make a deleted body live again. The component arrays stay under one World owner, and inspect returns a copied snapshot rather than a pointer that may outlive mutation.
Rust: the same contracts without shared entity ownership¶
Replace src/main.rs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
Rc::ptr_eq compares identity-marker allocations, not their equal unit values. Retaining a handle keeps that marker distinguishable after world destruction, without retaining the entity. checked_add makes generation exhaustion explicit. Option represents missing components and failed resolution without confusing them with valid zeros.
The Rust world can move as one owner while its marker remains shared with issued handles. It is not Clone; naively deriving Clone would copy its marker and stores, creating two worlds that both accept the same identity. The C++ fixture instead prohibits both copying and moving. These are deliberately different owner APIs, not evidence that every C++ world must be immovable. Private fields keep ordinary callers from fabricating handles or bypassing component cleanup; internal implementation code still bears responsibility for the invariant.
Changed requirement: should this become ECS?¶
The record loop keeps all of one body's data together. The component world separates Position and optional Velocity, with a movement system joining matching slots. It is a deliberately small ECS-style layout, not a generic engine, archetype allocator, scheduler or serialization format. Fixed slots avoid dense-store swap removal; a production dense store adds its own mapping and cleanup obligations.
The tested equality says both layouts implement these movement fixtures. It does not say the component layout is faster, clearer or less work to maintain. With only this rule, records may be the better choice. ECS becomes a candidate when independently combined capabilities and cross-entity processing justify managing joins, identities and execution order.
If acceleration is added, either design must specify acceleration-before-movement or another intended order. ECS makes system order an explicit responsibility; moving a function into a system does not settle the rule. Structural changes during iteration need a defined immediate/deferred policy. See the ECS execution-order chapter and component-store invariants.
If slot reuse is unnecessary, monotonic non-reused IDs can remove the generation/free-slot policy. If a reference need exist only during one borrowed operation, a reference may remove the ID lookup entirely. Conversely, Rc/Arc or shared_ptr owning the body would deliberately extend its lifetime; that is not equivalent to a handle that must stop resolving when the world deletes it.
Identity is not an authorization token or a database key. The marker cannot be meaningfully serialized as a pointer. Persistence, concurrent access, cross-world transfer and durable IDs require new contracts rather than silently exporting slot and generation as the complete identity.
Intentional failures: owner transfer is not owner duplication¶
This independent Rust example transfers an owner and then tries to use its former binding:
Use the transferred owner. If independent duplication is required, copy the data explicitly and issue a new identity domain; do not share the old marker merely to make Clone convenient.
The C++ analogue rejects a copy by its declared owner policy:
This is a deleted-copy rule, not Rust's deinitialized-binding mechanism. Copyable handles in the full examples are different from copying the world that owns the components.
Decision criteria and exercises¶
| Requirement | Start with | Obligation added |
|---|---|---|
| One owner, short-lived access | Owned record plus borrowed operation | Keep borrows within the owner's permitted mutation scope |
| Selection between operations | Owner-scoped non-reused ID | Resolve live membership and handle failed lookup |
| Recycle a bounded storage slot | Owner, slot and generation | Stale rejection, retirement and capacity exhaustion |
| Independently combined component processing | ECS-style stores and systems | Joins, complete cleanup, structural-change and execution-order rules |
| Independent persistent copy | Data snapshot or new world with new IDs | Define copied relationships and identity remapping |
- Remove the owner check while retaining the foreign-world test. The broken program compiles but must fail the identity contract.
- Remove the generation check while retaining the stale-copy test. Confirm that the old handle must not resolve to the replacement.
- Deliberately leave the old velocity behind on remove, and avoid overwriting velocity when inserting a body with None. Retain the reused-slot movement test to expose inherited components.
- Add acceleration to both record and component layouts. State the order, compare owned snapshots and separately decide whether the edit map favours either design.
- Design a no-reuse variant. Explain which tests remain relevant and why numeric ID exhaustion is still a policy even without generations.
Part 6 checkpoint: defend the design boundary¶
Revisit each decision with a changed requirement and a test, not a pattern name:
- Strategy: a policy now keeps a call count. Distinguish copying owned state from borrowing retained state; test inclusive boundaries and call order.
- State: opening may fail and must permit retry. Decide whether failure returns the consumed owner or retains state. Typestate restricts available operations; it does not force an eventual close.
- Factory/Builder: a new raw input path appears. Delegate validation and test omission, zero and cross-field precedence.
- Visitor: add a variant and an operation separately. Identify each place requiring a semantic decision; exhaustive handling does not prove correct handling.
- Observer: replace direct calls with queued delivery. Write capacity, fan-out, acknowledgement and shutdown policies before claiming equivalent behaviour.
- Ownership/IDs/ECS: require slot reuse. Test foreign, deleted and recycled identity, cleanup and retirement before deciding whether separate component stores are worth maintaining.
For each answer, name the owner, allowed mutation, failure result and change boundary. Defend when the simpler alternative should remain. These exercises complement the six Rust/C++ comparison contracts, not a benchmark ranking.
Verification and further study¶
The exact programs were verified on Raspberry Pi 4B with rustc/cargo 1.99.0, GCC 14.2.0 and kernel 6.18.50+rpt-rpi-v8. Rust passed six tests in debug and release, exact-source formatting and both output checks, plus the transferred-owner repair. The former owner failed with E0382. Three intentionally broken variants still compiled but failed debug tests for foreign identity, recycled identity or component cleanup. C++20 passed output/assertions and an additional owner/snapshot repair at -O0 and -O2, with assertions enabled; copying the declared noncopyable owner failed compilation. Both complete fixtures exercised retirement after all 256 generations without counter wrap. They do not prove all arithmetic, concurrency or allocator behaviour.
Continue with the C++ ECS design course for a connected simulation and writer traces. Return to the Rust language-course review to check how ownership, matching, visibility and library contracts relate to the language specification.