rustfront 1.0.0

Evaluate MFront material behaviours (constitutive laws) at a material point, in pure Rust, without any C++ build dependency
Documentation
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Loading a behaviour from a library generated by MFront, and integrating it
//! at one material point.

use core::ffi::{c_int, CStr};
use std::path::Path;

use libloading::Library;

use crate::symbols::Symbols;
use crate::{ffi, Error, Frame, Hypothesis, Rotated, Rotation};

/// The kind of a variable. With the hypothesis, it fixes the number of
/// components of the variable.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VariableType {
    /// One value.
    Scalar,
    /// As many components as the space dimension.
    Vector,
    /// Symmetric tensor: 3, 4 or 6 components, stored in TFEL's convention
    /// (`xx`, `yy`, `zz`, `√2·xy`, `√2·xz`, `√2·yz`).
    Stensor,
    /// Unsymmetric tensor: 3, 5 or 9 components, stored in TFEL's order and
    /// without factor: `xx yy zz xy yx xz zx yz zy` in 3D, `xx yy zz xy yx`
    /// in 2D, `rr zz tt rz zr` in axisymmetry, `rr zz tt` in 1D.
    Tensor,
}

/// The bounds of a variable, as MFront's `@Bounds` and `@PhysicalBounds`
/// give them, both included: `None` for no bound on that side.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Bounds {
    /// The lower bound.
    pub lower: Option<f64>,
    /// The upper bound.
    pub upper: Option<f64>,
}

/// A variable of the behaviour, and where its components sit in the array
/// that holds it.
#[derive(Clone, Debug, PartialEq)]
pub struct Variable {
    /// The name, such as `ElasticStrain` or `Temperature`.
    pub name: String,
    /// The kind.
    pub variable_type: VariableType,
    /// Position of the first component in the array.
    pub offset: usize,
    /// Number of components.
    pub size: usize,
    /// The bounds the out of bounds policy enforces, those of the array for
    /// an element of an array.
    pub bounds: Bounds,
    /// The physical bounds, always enforced: a temperature or a Young
    /// modulus is positive, for instance with `@UnitSystem SI`.
    pub physical_bounds: Bounds,
}

/// The variables stored one after the other in one array (gradients,
/// material properties, internal state variables, …).
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Variables {
    /// The variables, in the order of the array.
    pub list: Vec<Variable>,
    /// The length of the array: the sum of the sizes.
    pub size: usize,
}

/// The material symmetry of the behaviour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Symmetry {
    /// Isotropic.
    Isotropic,
    /// Orthotropic: gradients and thermodynamic forces are expressed in the
    /// material frame, the caller rotates them.
    Orthotropic,
}

/// The kind of behaviour, which fixes what its gradients and thermodynamic
/// forces are.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BehaviourType {
    /// A general behaviour (`@DSL DefaultGenericBehaviour`, …): the gradients,
    /// thermodynamic forces and tangent operator blocks it declares, whatever
    /// their names; point-wise models included, without gradient.
    General,
    /// A small strain behaviour: the strain, `Strain`, and the stress,
    /// `Stress`.
    SmallStrain,
    /// A finite strain behaviour: the deformation gradient,
    /// `DeformationGradient`, and the stress measure of the [`Settings`].
    FiniteStrain,
    /// A cohesive zone model: the opening displacement, `OpeningDisplacement`,
    /// and the cohesive force, `CohesiveForce`, two vectors whose first
    /// component is normal to the interface, the others tangential.
    CohesiveZoneModel,
}

/// The kinematic of a behaviour, as MFront declares it (`_BehaviourKinematic`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kinematic {
    /// None in particular: a general behaviour, a point-wise model.
    Undefined,
    /// Small strain: the strain and the stress.
    SmallStrain,
    /// A cohesive zone model: the opening displacement and the cohesive
    /// force.
    CohesiveZone,
    /// Finite strain: the deformation gradient and the Cauchy stress, as the
    /// `generic` interface gives them.
    FiniteStrainFCauchy,
    /// Finite strain through a strain measure: a strain and its dual stress.
    FiniteStrainEtoPk1,
}

/// The value of a parameter, of one of the three types MFront supports.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParameterValue {
    /// A real parameter, such as `epsilon`.
    Real(f64),
    /// An integer parameter.
    Integer(i32),
    /// An unsigned short parameter, such as `iterMax`.
    UnsignedShort(u16),
}

/// A parameter of the behaviour: a value fixed in the library, which
/// [`Settings`] can change at load.
#[derive(Clone, Debug, PartialEq)]
pub struct Parameter {
    /// The name, such as `epsilon` or `b[0]` for an element of an array.
    pub name: String,
    /// The value given in the MFront file; its type is the parameter's.
    pub default: ParameterValue,
}

/// What a behaviour or material property does when a variable leaves the
/// bounds its author gave. Physical bounds are always enforced.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutOfBoundsPolicy {
    /// Nothing.
    None,
    /// A behaviour prints a warning and integrates; a material property
    /// computes its value and reports the variable, see
    /// [`crate::Evaluation::out_of_bounds`].
    Warning,
    /// The integration or the evaluation fails.
    Strict,
}

impl OutOfBoundsPolicy {
    /// The code both C interfaces use: 0 None, 1 Warning, 2 Strict.
    pub(crate) fn code(self) -> c_int {
        match self {
            OutOfBoundsPolicy::None => 0,
            OutOfBoundsPolicy::Warning => 1,
            OutOfBoundsPolicy::Strict => 2,
        }
    }
}

/// The stress a finite strain behaviour computes, in the thermodynamic
/// forces.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StressMeasure {
    /// The Cauchy stress, a symmetric tensor named `Stress`.
    #[default]
    Cauchy,
    /// The second Piola-Kirchhoff stress, a symmetric tensor named
    /// `SecondPiolaKirchhoffStress`.
    SecondPiolaKirchhoff,
    /// The first Piola-Kirchhoff stress, an unsymmetric tensor named
    /// `FirstPiolaKirchhoffStress`.
    FirstPiolaKirchhoff,
}

/// The tangent operator a finite strain behaviour computes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FiniteStrainTangentOperator {
    /// The derivative of the Cauchy stress with respect to the deformation
    /// gradient, `DSIG_DF` for MFront.
    #[default]
    CauchyByDeformationGradient,
    /// The derivative of the second Piola-Kirchhoff stress with respect to
    /// the Green-Lagrange strain, `DS_DEGL`.
    SecondPiolaKirchhoffByGreenLagrange,
    /// The derivative of the first Piola-Kirchhoff stress with respect to
    /// the deformation gradient, `DPK1_DF`.
    FirstPiolaKirchhoffByDeformationGradient,
    /// The derivative of the Kirchhoff stress with respect to the spatial
    /// increment of the deformation gradient, `DTAU_DDF`.
    KirchhoffBySpatialIncrement,
}

/// What [`Behaviour::load`] changes in the library: the values of
/// parameters, and the out of bounds policy; and, for a finite strain
/// behaviour, the stress and the tangent operator to compute.
///
/// Both are static variables of the library, shared by every `Behaviour`
/// loaded from it for the same behaviour: the last load wins.
///
/// ```
/// use rustfront::{OutOfBoundsPolicy, ParameterValue, Settings};
///
/// let settings = Settings {
///     parameters: &[("epsilon", ParameterValue::Real(1e-12))],
///     out_of_bounds_policy: Some(OutOfBoundsPolicy::Strict),
///     ..Default::default()
/// };
/// // Nothing changed: the values and the policy of the library.
/// let defaults = Settings::default();
/// assert!(defaults.parameters.is_empty() && defaults.out_of_bounds_policy.is_none());
/// # let _ = settings;
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct Settings<'a> {
    /// Parameters to set, by name, with a value of their type.
    pub parameters: &'a [(&'a str, ParameterValue)],
    /// The policy to set; `None` keeps the one of the library.
    pub out_of_bounds_policy: Option<OutOfBoundsPolicy>,
    /// For a finite strain behaviour, the stress in the thermodynamic forces:
    /// the Cauchy stress by default.
    pub stress_measure: StressMeasure,
    /// For a finite strain behaviour, the tangent operator: the derivative
    /// of the Cauchy stress with respect to the deformation gradient by
    /// default.
    pub finite_strain_tangent_operator: FiniteStrainTangentOperator,
}

/// What the behaviour declares about itself, read from the library by
/// [`Behaviour::load`].
#[derive(Clone, Debug, PartialEq)]
pub struct Description {
    /// The name of the behaviour.
    pub name: String,
    /// The hypothesis it was loaded for.
    pub hypothesis: Hypothesis,
    /// The TFEL version that generated the library.
    pub tfel_version: String,
    /// The MFront file it was generated from, such as `Norton.mfront`.
    pub source: String,
    /// What the MFront file says of itself (`@Author`, `@Date`,
    /// `@Description`), who validated it and the identifier of its build:
    /// empty when it says nothing, as MFront exports them.
    pub author: String,
    /// See [`Description::author`].
    pub date: String,
    /// See [`Description::author`].
    pub description: String,
    /// See [`Description::author`].
    pub validator: String,
    /// See [`Description::author`].
    pub build_id: String,
    /// The unit system of `@UnitSystem`, such as `SI`: empty when there is
    /// none.
    pub unit_system: String,
    /// The kind of behaviour.
    pub behaviour_type: BehaviourType,
    /// Its kinematic.
    pub kinematic: Kinematic,
    /// Whether the behaviour computes its stored energy (`@InternalEnergy`)
    /// and its dissipated energy (`@DissipatedEnergy`) at the end of the
    /// step; otherwise, they are left as the caller gives them.
    pub computes_stored_energy: bool,
    /// See [`Description::computes_stored_energy`].
    pub computes_dissipated_energy: bool,
    /// The material symmetry.
    pub symmetry: Symmetry,
    /// The gradients: `Strain` for a small strain behaviour.
    pub gradients: Variables,
    /// The thermodynamic forces, dual of the gradients: `Stress`.
    pub thermodynamic_forces: Variables,
    /// The material properties. When the behaviour computes its stiffness or
    /// thermal expansion tensor itself, the elastic properties
    /// (`YoungModulus`, `PoissonRatio`, …) and thermal expansion coefficients
    /// come first.
    pub material_properties: Variables,
    /// The internal state variables, auxiliary ones included.
    pub internal_state_variables: Variables,
    /// The external state variables, `Temperature` first.
    pub external_state_variables: Variables,
    /// The blocks of the tangent operator, as pairs (derivative of, with
    /// respect to), such as (`Stress`, `Strain`). They are stored one after
    /// the other, each row major.
    pub tangent_operator_blocks: Vec<(String, String)>,
    /// The length of the tangent operator array: the sum of the block sizes.
    pub tangent_operator_size: usize,
    /// The parameters, with the values the MFront file gives them: those
    /// [`Settings`] changed are not read back.
    pub parameters: Vec<Parameter>,
}

/// What an integration computes, as MGIS's `IntegrationType`, the code the
/// behaviour reads in `K[0]`.
///
/// The prediction operators come alone: the behaviour computes one from the
/// state at the beginning of the step and the gradients and external state
/// variables at its end, and integrates nothing; the thermodynamic forces,
/// the internal state variables and the energies at the end are left as
/// they were. Not every behaviour provides them, nor every operator:
/// [`Error::IntegrationFailed`] otherwise.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[expect(
    clippy::enum_variant_names,
    reason = "the names of MGIS's IntegrationType, which all end with Operator"
)]
pub enum IntegrationType {
    /// The tangent prediction operator, alone: `-3`.
    PredictionTangentOperator,
    /// The secant prediction operator, alone: `-2`.
    PredictionSecantOperator,
    /// The elastic prediction operator, alone: `-1`.
    PredictionElasticOperator,
    /// The integration, without operator: `0`.
    IntegrationNoTangentOperator,
    /// The integration and the elastic operator: `1`.
    IntegrationElasticOperator,
    /// The integration and the secant operator: `2`.
    IntegrationSecantOperator,
    /// The integration and the tangent operator: `3`.
    IntegrationTangentOperator,
    /// The integration and the consistent tangent operator, the one a
    /// Newton-Raphson algorithm needs: `4`.
    #[default]
    IntegrationConsistentTangentOperator,
}

/// The options of an integration, as MGIS's `BehaviourIntegrationOptions`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct IntegrationOptions {
    /// What is computed: the integration and the consistent tangent operator
    /// by default.
    pub integration_type: IntegrationType,
    /// Whether the behaviour also computes the speed of sound, into
    /// [`BehaviourData::speed_of_sound`], from the mass density at the end of
    /// the step, or at its beginning for a prediction operator: 100 more in
    /// `K[0]`. It is zero for a behaviour without `@SpeedOfSound`.
    pub compute_speed_of_sound: bool,
}

/// How a successful integration went, as the value MGIS's `integrate`
/// returns, its failure being an [`Error::IntegrationFailed`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
    /// The results are reliable: `1`.
    Reliable,
    /// The results are accepted, but the behaviour proposes a smaller time
    /// step, [`BehaviourData::rdt`] being below 0.99: `0`.
    Unreliable,
}

/// The state at the beginning of the time step, borrowed from the caller, as
/// MGIS's `InitialStateView`.
///
/// Every array must have the length the [`Description`] gives.
#[derive(Clone, Copy, Debug, Default)]
pub struct InitialState<'a> {
    /// The gradients.
    pub gradients: &'a [f64],
    /// The thermodynamic forces.
    pub thermodynamic_forces: &'a [f64],
    /// The mass density in the reference configuration, for the speed of
    /// sound of a prediction operator.
    pub mass_density: f64,
    /// The material properties.
    pub material_properties: &'a [f64],
    /// The internal state variables.
    pub internal_state_variables: &'a [f64],
    /// The stored energy, for behaviours that compute it.
    pub stored_energy: f64,
    /// The dissipated energy, for behaviours that compute it.
    pub dissipated_energy: f64,
    /// The external state variables, temperature first.
    pub external_state_variables: &'a [f64],
}

/// The state at the end of the time step, borrowed from the caller, as
/// MGIS's `StateView`: the caller gives the gradients, the mass density, the
/// material properties and the external state variables, the behaviour
/// writes the thermodynamic forces, the internal state variables and the
/// energies it computes ([`Description::computes_stored_energy`]).
///
/// Every array must have the length the [`Description`] gives.
#[derive(Debug, Default)]
pub struct FinalState<'a> {
    /// The gradients.
    pub gradients: &'a [f64],
    /// The thermodynamic forces, written by the behaviour.
    pub thermodynamic_forces: &'a mut [f64],
    /// The mass density in the reference configuration, for the speed of
    /// sound.
    pub mass_density: f64,
    /// The material properties.
    pub material_properties: &'a [f64],
    /// The internal state variables, written by the behaviour.
    pub internal_state_variables: &'a mut [f64],
    /// The stored energy, written by a behaviour that computes it.
    pub stored_energy: f64,
    /// The dissipated energy, written by a behaviour that computes it.
    pub dissipated_energy: f64,
    /// The external state variables, temperature first.
    pub external_state_variables: &'a [f64],
}

/// The data of an integration at one material point, borrowed from the
/// caller, as MGIS's `BehaviourDataView`: [`Behaviour::integrate`] reads
/// them and writes the results in place.
#[derive(Debug)]
pub struct BehaviourData<'a> {
    /// The time increment.
    pub dt: f64,
    /// Given, the largest factor by which the behaviour may propose to scale
    /// the time step (1 forbids a larger one); written, the factor it
    /// proposes, also when it fails.
    pub rdt: f64,
    /// The operator the [`IntegrationOptions`] ask for, written by the
    /// behaviour: [`Description::tangent_operator_size`] values, the blocks
    /// of [`Description::tangent_operator_blocks`] one after the other, each
    /// row major. Empty when none is asked.
    pub k: &'a mut [f64],
    /// The speed of sound, written when the [`IntegrationOptions`] ask for
    /// it.
    pub speed_of_sound: f64,
    /// The state at the beginning of the time step.
    pub s0: InitialState<'a>,
    /// The state at the end of the time step.
    pub s1: FinalState<'a>,
}

/// The rotations of a behaviour, or why it has none.
#[derive(Debug)]
enum Rotations {
    /// An isotropic behaviour exports none.
    Isotropic,
    /// An orthotropic behaviour with this vector to rotate, which the
    /// rotations TFEL 5.1 generates do not support.
    Vector(String),
    /// The rotations of the gradients (from the global frame to the material
    /// one), of the thermodynamic forces and of the tangent operator (from
    /// the material frame to the global one).
    Functions([ffi::RotateFn; 3]),
}

/// A behaviour loaded from a library generated by MFront with the `generic`
/// interface, for one modelling hypothesis.
///
/// It can be shared between threads: integrating does not modify it.
#[derive(Debug)]
pub struct Behaviour {
    description: Description,
    integrate: ffi::IntegrateFn,
    /// For a finite strain behaviour, `K[1]` and `K[2]`: the codes of the
    /// stress measure and of the tangent operator it reads.
    finite_strain: Option<[f64; 2]>,
    rotations: Rotations,
    /// Keeps the library loaded as long as `integrate` can be called.
    _library: Library,
}

impl Behaviour {
    /// Loads the behaviour `name` from `library` for `hypothesis`, reads its
    /// [`Description`], then applies the `settings`.
    ///
    /// ```no_run
    /// use rustfront::{Behaviour, Hypothesis, ParameterValue, Settings};
    ///
    /// // SAFETY: `libBehaviour.so` was generated by `mfront --interface=generic`,
    /// // and no integration of Norton runs meanwhile.
    /// let norton = unsafe {
    ///     Behaviour::load("src/libBehaviour.so", "Norton", Hypothesis::Tridimensional,
    ///         &Settings {
    ///             parameters: &[("epsilon", ParameterValue::Real(1e-12))],
    ///             ..Default::default()
    ///         })?
    /// };
    /// assert_eq!(norton.description().gradients.size, 6);
    /// # Ok::<(), rustfront::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// When the library cannot be opened, when a symbol is missing, and when
    /// the behaviour is not supported: interface other than `generic`, TFEL
    /// older than 5.1.0, version of the interface other than 1, unknown kind
    /// of behaviour, hypothesis not provided, variable of an unsupported type,
    /// finite strain settings for another behaviour. When a setting cannot be
    /// applied: unknown parameter, value of another type, value refused by the
    /// behaviour.
    ///
    /// # Safety
    ///
    /// Opening a library runs its initialisation code, and the symbols it
    /// exports are trusted to have the types MFront gives them: `library`
    /// must be a library generated by MFront, which is not modified while the
    /// returned `Behaviour` lives.
    ///
    /// The settings change static variables of the library: no integration of
    /// this behaviour, by any `Behaviour` loaded from the same library, may
    /// run during the call.
    pub unsafe fn load(
        library: impl AsRef<Path>,
        name: &str,
        hypothesis: Hypothesis,
        settings: &Settings<'_>,
    ) -> Result<Self, Error> {
        let path = library.as_ref();
        // SAFETY: the caller guarantees that the library is a genuine MFront
        // library, whose initialisation code is safe to run.
        let library = unsafe { Library::new(path) }.map_err(|source| Error::Open {
            library: path.to_path_buf(),
            source,
        })?;
        let h = hypothesis.name();
        let symbols = Symbols {
            library: &library,
            name,
            hypothesis: Some(h),
        };
        let dimension = hypothesis.space_dimension();

        // Is this a behaviour this crate can call?
        let tfel_version = symbols.check(1)?;
        let version = symbols.u16("api_version")?;
        if version != 1 {
            return Err(Error::UnsupportedApiVersion {
                name: name.to_owned(),
                version,
            });
        }
        let behaviour_type = match symbols.u16("BehaviourType")? {
            0 => BehaviourType::General,
            1 => BehaviourType::SmallStrain,
            2 => BehaviourType::FiniteStrain,
            3 => BehaviourType::CohesiveZoneModel,
            code => {
                return Err(Error::UnsupportedBehaviourType {
                    name: name.to_owned(),
                    code,
                })
            }
        };
        // A finite strain behaviour, its own or through a strain measure: the
        // generic interface gives it the deformation gradient and the Cauchy
        // stress.
        let finite_strain = behaviour_type == BehaviourType::FiniteStrain;
        if !finite_strain
            && (settings.stress_measure != StressMeasure::default()
                || settings.finite_strain_tangent_operator
                    != FiniteStrainTangentOperator::default())
        {
            return Err(Error::FiniteStrainSettings {
                name: name.to_owned(),
            });
        }
        let n = usize::from(symbols.u16("nModellingHypotheses")?);
        let supported = symbols.strings("ModellingHypotheses", n)?;
        if !supported.iter().any(|s| s == h) {
            return Err(Error::UnsupportedHypothesis {
                name: name.to_owned(),
                hypothesis,
                supported,
            });
        }
        let kinematic = match symbols.u16("BehaviourKinematic")? {
            1 => Kinematic::SmallStrain,
            2 => Kinematic::CohesiveZone,
            3 => Kinematic::FiniteStrainFCauchy,
            4 => Kinematic::FiniteStrainEtoPk1,
            _ => Kinematic::Undefined,
        };
        let text = |suffix| symbols.strings(suffix, 1).map(|mut s| s.remove(0));
        let symmetry = match symbols.u16("SymmetryType")? {
            0 => Symmetry::Isotropic,
            _ => Symmetry::Orthotropic,
        };

        // The variables, in the arrays the integration function reads. The
        // elastic properties and thermal expansion coefficients of a behaviour
        // that computes these tensors itself, then the temperature, are not
        // listed by the library but expected first, as MGIS does.
        let gradients = layout(symbols.variables("Gradients", true)?, dimension, &symbols);
        // What the settings choose for a finite strain behaviour: the stress,
        // named as MGIS does, its code in `K[1]` and the suffix of its
        // rotation; the tangent operator block, its code in `K[2]` and the
        // suffix of its rotation.
        let (stress, stress_code, stress_rotation) = match settings.stress_measure {
            StressMeasure::Cauchy => (("Stress", VariableType::Stensor), 0.0, "CauchyStress"),
            StressMeasure::SecondPiolaKirchhoff => (
                ("SecondPiolaKirchhoffStress", VariableType::Stensor),
                1.0,
                "PK2Stress",
            ),
            StressMeasure::FirstPiolaKirchhoff => (
                ("FirstPiolaKirchhoffStress", VariableType::Tensor),
                2.0,
                "PK1Stress",
            ),
        };
        let (block, tangent_code, tangent_rotation) = match settings.finite_strain_tangent_operator
        {
            FiniteStrainTangentOperator::CauchyByDeformationGradient => (
                [
                    ("Stress", VariableType::Stensor),
                    ("DeformationGradient", VariableType::Tensor),
                ],
                0.0,
                "dsig_dF",
            ),
            FiniteStrainTangentOperator::SecondPiolaKirchhoffByGreenLagrange => (
                [
                    ("SecondPiolaKirchhoffStress", VariableType::Stensor),
                    ("GreenLagrangeStrain", VariableType::Stensor),
                ],
                1.0,
                "dPK2_dEGL",
            ),
            FiniteStrainTangentOperator::FirstPiolaKirchhoffByDeformationGradient => (
                [
                    ("FirstPiolaKirchhoffStress", VariableType::Tensor),
                    ("DeformationGradient", VariableType::Tensor),
                ],
                2.0,
                "dPK1_dF",
            ),
            FiniteStrainTangentOperator::KirchhoffBySpatialIncrement => (
                [
                    ("KirchhoffStress", VariableType::Stensor),
                    (
                        "SpatialIncrementOfTheDeformationGradient",
                        VariableType::Tensor,
                    ),
                ],
                3.0,
                "dtau_ddF",
            ),
        };
        let thermodynamic_forces = if finite_strain {
            vec![(stress.0.to_owned(), stress.1)]
        } else {
            symbols.variables("ThermodynamicForces", true)?
        };
        let thermodynamic_forces = layout(thermodynamic_forces, dimension, &symbols);
        let mut material_properties = Vec::new();
        let mut scalars = |names: &[&str]| {
            material_properties.extend(names.iter().map(|n| (n.to_string(), VariableType::Scalar)));
        };
        if symbols.u16("requiresStiffnessTensor")? == 1 {
            if symbols.u16("ElasticSymmetryType")? == 0 {
                scalars(&["YoungModulus", "PoissonRatio"]);
            } else {
                scalars(&["YoungModulus1", "YoungModulus2", "YoungModulus3"]);
                scalars(&["PoissonRatio12", "PoissonRatio23", "PoissonRatio13"]);
                match dimension {
                    1 => {}
                    2 => scalars(&["ShearModulus12"]),
                    _ => scalars(&["ShearModulus12", "ShearModulus23", "ShearModulus13"]),
                }
            }
        }
        if symbols.u16("requiresThermalExpansionCoefficientTensor")? == 1 {
            match symmetry {
                Symmetry::Isotropic => scalars(&["ThermalExpansion"]),
                Symmetry::Orthotropic => scalars(&[
                    "ThermalExpansion1",
                    "ThermalExpansion2",
                    "ThermalExpansion3",
                ]),
            }
        }
        material_properties.extend(symbols.variables("MaterialProperties", false)?);
        let material_properties = layout(material_properties, dimension, &symbols);
        let internal_state_variables = layout(
            symbols.variables("InternalStateVariables", true)?,
            dimension,
            &symbols,
        );
        let mut external_state_variables = Vec::new();
        if symbols.u16("TemperatureRemovedFromExternalStateVariables")? == 1 {
            external_state_variables.push(("Temperature".to_owned(), VariableType::Scalar));
        }
        external_state_variables.extend(symbols.variables("ExternalStateVariables", true)?);
        let external_state_variables = layout(external_state_variables, dimension, &symbols);

        // The tangent operator: blocks (derivative of, with respect to). That
        // of a finite strain behaviour is the one the settings choose, named
        // as MGIS does; the others are listed as a flat array of names.
        let (tangent_operator_blocks, tangent_operator_size) = if finite_strain {
            let block = layout(
                block.map(|(n, t)| (n.to_owned(), t)).to_vec(),
                dimension,
                &symbols,
            );
            let size = block.list[0].size * block.list[1].size;
            let [of, with_respect_to] = [0, 1].map(|i| block.list[i].name.clone());
            (vec![(of, with_respect_to)], size)
        } else {
            let n = usize::from(symbols.u16("nTangentOperatorBlocks")?);
            let names = symbols.strings("TangentOperatorBlocks", n)?;
            let mut size = 0;
            let mut blocks = Vec::new();
            for [of, with_respect_to] in names.as_chunks::<2>().0 {
                // The block size: the product of the sizes of its two
                // variables, which the behaviour declares.
                let mut block = 1;
                for variable in [of, with_respect_to] {
                    block *= [
                        &gradients,
                        &thermodynamic_forces,
                        &internal_state_variables,
                        &external_state_variables,
                    ]
                    .iter()
                    .flat_map(|v| &v.list)
                    .find(|v| &v.name == variable)
                    .expect("MFront names the variables of the tangent operator blocks")
                    .size;
                }
                size += block;
                blocks.push((of.clone(), with_respect_to.clone()));
            }
            (blocks, size)
        };

        // The rotations of an orthotropic behaviour: of the gradients, of the
        // thermodynamic forces and of the tangent operator, those of the
        // stress and tangent operator of the settings for a finite strain
        // behaviour. The functions TFEL 5.1 generates end the process when
        // they meet a vector: the gradients, the thermodynamic forces, and
        // the variables of the blocks are checked first.
        let vector = gradients
            .list
            .iter()
            .chain(&thermodynamic_forces.list)
            .chain(
                internal_state_variables
                    .list
                    .iter()
                    .chain(&external_state_variables.list)
                    .filter(|v| {
                        tangent_operator_blocks.iter().any(|(of, with_respect_to)| {
                            *of == v.name || *with_respect_to == v.name
                        })
                    }),
            )
            .find(|v| v.variable_type == VariableType::Vector);
        let rotations = match (symmetry, vector) {
            (Symmetry::Isotropic, _) => Rotations::Isotropic,
            (Symmetry::Orthotropic, Some(v)) => Rotations::Vector(v.name.clone()),
            (Symmetry::Orthotropic, None) => {
                let [forces, tangent] = if finite_strain {
                    [
                        format!("rotateArrayOfThermodynamicForces_{stress_rotation}"),
                        format!("rotateArrayOfTangentOperatorBlocks_{tangent_rotation}"),
                    ]
                } else {
                    [
                        "rotateArrayOfThermodynamicForces".to_owned(),
                        "rotateArrayOfTangentOperatorBlocks".to_owned(),
                    ]
                };
                // SAFETY: MFront exports these functions, for an orthotropic
                // behaviour, with the signature of `ffi::RotateFn`.
                Rotations::Functions(unsafe {
                    [
                        symbols.get("rotateArrayOfGradients")?,
                        symbols.get(&forces)?,
                        symbols.get(&tangent)?,
                    ]
                })
            }
        };

        // The parameters, then the settings, in the static variables of the
        // library.
        let parameters = symbols.parameters()?;
        // SAFETY: the caller guarantees that no integration runs meanwhile.
        unsafe { symbols.set_parameters(&parameters, settings.parameters)? };
        if let Some(policy) = settings.out_of_bounds_policy {
            // SAFETY: MFront exports this function with the signature of
            // `ffi`; as above, nothing runs meanwhile.
            unsafe {
                symbols.get::<ffi::SetOutOfBoundsPolicyFn>("setOutOfBoundsPolicy")?(policy.code())
            };
        }

        let symbol = format!("{name}_{h}");
        // SAFETY: MFront exports `<behaviour>_<hypothesis>` with the signature
        // of `ffi::IntegrateFn`. The pointer stays valid as long as the library
        // is loaded, which `_library` guarantees.
        let integrate = *unsafe { library.get::<ffi::IntegrateFn>(symbol.as_str()) }
            .map_err(|_| Error::MissingSymbol { symbol })?;
        Ok(Behaviour {
            description: Description {
                name: name.to_owned(),
                hypothesis,
                tfel_version,
                source: text("src")?,
                author: text("author")?,
                date: text("date")?,
                description: text("description")?,
                validator: text("validator")?,
                build_id: text("build_id")?,
                unit_system: text("unit_system")?,
                behaviour_type,
                kinematic,
                computes_stored_energy: symbols.u16("ComputesInternalEnergy")? == 1,
                computes_dissipated_energy: symbols.u16("ComputesDissipatedEnergy")? == 1,
                symmetry,
                gradients,
                thermodynamic_forces,
                material_properties,
                internal_state_variables,
                external_state_variables,
                tangent_operator_blocks,
                tangent_operator_size,
                parameters,
            },
            integrate,
            finite_strain: finite_strain.then_some([stress_code, tangent_code]),
            rotations,
            _library: library,
        })
    }

    /// Rotates `values`, the gradients, the thermodynamic forces or the
    /// tangent operator as `what` says, to the frame `to`, in place: as many
    /// points as they hold, stored one after the other. An orthotropic
    /// behaviour integrates in its material frame: its gradients, and its
    /// thermodynamic forces at the beginning of the step, are rotated to it
    /// before [`Behaviour::integrate`], the thermodynamic forces and the
    /// tangent operator it computes back to the global frame after.
    ///
    /// ```no_run
    /// use rustfront::{Behaviour, Frame, Hypothesis, Rotated, Rotation, Settings};
    ///
    /// // SAFETY: `libBehaviour.so` was generated by `mfront --interface=generic`.
    /// let behaviour = unsafe {
    ///     Behaviour::load("src/libBehaviour.so", "OrthotropicElasticity",
    ///         Hypothesis::Tridimensional, &Settings::default())?
    /// };
    /// // The material axes at 30° from x and y, about z.
    /// let (s, c) = 30_f64.to_radians().sin_cos();
    /// let r = Rotation::from_axes([c, s, 0.0], [-s, c, 0.0])?;
    /// // Two points, their strains in the global frame.
    /// let mut strains = [1e-3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2e-3, 0.0, 0.0, 0.0, 0.0];
    /// behaviour.rotate(Rotated::Gradients, &r, Frame::Material, &mut strains)?;
    /// // … integrate each point, then rotate its stress and its tangent
    /// // operator back to the global frame:
    /// // behaviour.rotate(Rotated::ThermodynamicForces, &r, Frame::Global, &mut stresses)?;
    /// // behaviour.rotate(Rotated::TangentOperator, &r, Frame::Global, &mut k)?;
    /// # Ok::<(), rustfront::Error>(())
    /// ```
    ///
    /// The internal state variables are not rotated: they stay in the
    /// material frame.
    ///
    /// For a finite strain behaviour, `r` is the material frame in the
    /// reference configuration, constant over time: the deformation gradient
    /// is rotated on both sides, and the behaviour follows the rotation of
    /// the material through it. Axes already turned with the material would
    /// count its rotation twice.
    ///
    /// # Errors
    ///
    /// [`Error::IncompletePoint`] when `values` does not hold whole points,
    /// [`Error::NotOrthotropic`] for an isotropic behaviour, which needs no
    /// rotation, [`Error::UnsupportedRotation`] when a variable to rotate is a
    /// vector.
    pub fn rotate(
        &self,
        what: Rotated,
        r: &Rotation,
        to: Frame,
        values: &mut [f64],
    ) -> Result<(), Error> {
        let d = &self.description;
        let [gradients, forces, tangent] = match &self.rotations {
            Rotations::Isotropic => {
                return Err(Error::NotOrthotropic {
                    name: d.name.clone(),
                });
            }
            Rotations::Vector(variable) => {
                return Err(Error::UnsupportedRotation {
                    name: d.name.clone(),
                    variable: variable.clone(),
                });
            }
            Rotations::Functions(functions) => *functions,
        };
        // The function, the array, the size of one point, and the frame the
        // function rotates to: to the other one with the transposed matrix.
        let (function, array, size, native) = match what {
            Rotated::Gradients => (gradients, "gradients", d.gradients.size, Frame::Material),
            Rotated::ThermodynamicForces => (
                forces,
                "thermodynamic forces",
                d.thermodynamic_forces.size,
                Frame::Global,
            ),
            Rotated::TangentOperator => (
                tangent,
                "tangent operator",
                d.tangent_operator_size,
                Frame::Global,
            ),
        };
        // A point-wise model has no gradient.
        let points = values.len().checked_div(size).unwrap_or(0);
        if points * size != values.len() {
            return Err(Error::IncompletePoint {
                array,
                size,
                found: values.len(),
            });
        }
        let m = r.matrix;
        let matrix = if to == native {
            m.concat()
        } else {
            (0..9).map(|k| m[k % 3][k / 3]).collect()
        };
        let values = values.as_mut_ptr();
        // SAFETY: MFront exports the function with the signature of
        // `ffi::RotateFn`. It reads the 9 values of `matrix` and `points`
        // points of `values`, and writes them in place, which it supports.
        unsafe { function(values, values, matrix.as_ptr(), points) };
        Ok(())
    }

    /// What the behaviour declares about itself: its variables and the
    /// length of each array [`Behaviour::integrate`] expects.
    pub fn description(&self) -> &Description {
        &self.description
    }

    /// Integrates the behaviour over the time step `d.dt`, from the state
    /// `d.s0` to the state `d.s1`, as MGIS's `integrate`, and computes what
    /// the `options` ask: an operator into `d.k`, the speed of sound into
    /// `d.speed_of_sound`. The behaviour writes, in `d.s1`, the
    /// thermodynamic forces, the internal state variables and the energies
    /// it computes, and in `d.rdt` the factor by which it proposes to scale
    /// the time step. A prediction operator is computed alone, nothing
    /// integrated.
    ///
    /// The gradient of a finite strain behaviour is the deformation gradient
    /// F, a [`VariableType::Tensor`]: at rest, the identity, `[1.0, 1.0, 1.0,
    /// 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]` in 3D. Its thermodynamic forces and
    /// tangent operator are those [`Settings`] chose at load, as the
    /// [`Description`] names them. A point-wise model has no operator: it is
    /// integrated with [`IntegrationType::IntegrationNoTangentOperator`].
    ///
    /// ```no_run
    /// use rustfront::{
    ///     Behaviour, BehaviourData, FinalState, Hypothesis, InitialState, IntegrationOptions,
    ///     Settings, Status,
    /// };
    ///
    /// // SAFETY: `libBehaviour.so` was generated by `mfront --interface=generic`.
    /// let norton = unsafe {
    ///     Behaviour::load("src/libBehaviour.so", "Norton", Hypothesis::Tridimensional,
    ///         &Settings::default())?
    /// };
    /// let d = norton.description();
    /// // NortonCoefficient, NortonExponent, YoungModulus, PoissonRatio.
    /// let material = [8e-67, 8.2, 150e9, 0.3];
    /// let temperature = [293.15];
    /// let isv0 = vec![0.0; d.internal_state_variables.size];
    /// let mut isv1 = isv0.clone();
    /// let (eps0, eps1) = ([0.0; 6], [1e-3, 0.0, 0.0, 0.0, 0.0, 0.0]);
    /// let (sig0, mut sig1) = ([0.0; 6], [0.0; 6]);
    /// let mut k = vec![0.0; d.tangent_operator_size];
    /// let mut data = BehaviourData {
    ///     dt: 1.0,
    ///     rdt: 1.0,
    ///     k: &mut k,
    ///     speed_of_sound: 0.0,
    ///     s0: InitialState {
    ///         gradients: &eps0,
    ///         thermodynamic_forces: &sig0,
    ///         material_properties: &material,
    ///         internal_state_variables: &isv0,
    ///         external_state_variables: &temperature,
    ///         ..Default::default()
    ///     },
    ///     s1: FinalState {
    ///         gradients: &eps1,
    ///         thermodynamic_forces: &mut sig1,
    ///         material_properties: &material,
    ///         internal_state_variables: &mut isv1,
    ///         external_state_variables: &temperature,
    ///         ..Default::default()
    ///     },
    /// };
    /// // The integration and the consistent tangent operator, by default.
    /// let status = norton.integrate(&mut data, IntegrationOptions::default())?;
    /// assert_eq!(status, Status::Reliable);
    /// # Ok::<(), rustfront::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::WrongLength`] when an array does not have the length the
    /// [`Description`] gives, `d.k` too unless no operator is asked and it
    /// is empty; [`Error::IntegrationFailed`] when the behaviour fails.
    pub fn integrate(
        &self,
        d: &mut BehaviourData<'_>,
        options: IntegrationOptions,
    ) -> Result<Status, Error> {
        let description = &self.description;
        let BehaviourData {
            dt,
            rdt,
            k,
            speed_of_sound,
            s0,
            s1,
        } = d;
        let code = match options.integration_type {
            IntegrationType::PredictionTangentOperator => -3.0,
            IntegrationType::PredictionSecantOperator => -2.0,
            IntegrationType::PredictionElasticOperator => -1.0,
            IntegrationType::IntegrationNoTangentOperator => 0.0,
            IntegrationType::IntegrationElasticOperator => 1.0,
            IntegrationType::IntegrationSecantOperator => 2.0,
            IntegrationType::IntegrationTangentOperator => 3.0,
            IntegrationType::IntegrationConsistentTangentOperator => 4.0,
        };
        let no_operator = code == 0.0 && k.is_empty();
        let lengths = [
            (
                "s0.gradients",
                description.gradients.size,
                s0.gradients.len(),
            ),
            (
                "s1.gradients",
                description.gradients.size,
                s1.gradients.len(),
            ),
            (
                "s0.thermodynamic_forces",
                description.thermodynamic_forces.size,
                s0.thermodynamic_forces.len(),
            ),
            (
                "s1.thermodynamic_forces",
                description.thermodynamic_forces.size,
                s1.thermodynamic_forces.len(),
            ),
            (
                "s0.material_properties",
                description.material_properties.size,
                s0.material_properties.len(),
            ),
            (
                "s1.material_properties",
                description.material_properties.size,
                s1.material_properties.len(),
            ),
            (
                "s0.internal_state_variables",
                description.internal_state_variables.size,
                s0.internal_state_variables.len(),
            ),
            (
                "s1.internal_state_variables",
                description.internal_state_variables.size,
                s1.internal_state_variables.len(),
            ),
            (
                "s0.external_state_variables",
                description.external_state_variables.size,
                s0.external_state_variables.len(),
            ),
            (
                "s1.external_state_variables",
                description.external_state_variables.size,
                s1.external_state_variables.len(),
            ),
            (
                "k",
                if no_operator {
                    0
                } else {
                    description.tangent_operator_size
                },
                k.len(),
            ),
        ];
        if let Some(&(array, expected, found)) = lengths.iter().find(|(_, e, f)| e != f) {
            return Err(Error::WrongLength {
                array,
                expected,
                found,
            });
        }
        // `K[0]` tells the behaviour what to compute, 100 more for the speed
        // of sound; a finite strain behaviour reads its stress measure and
        // tangent operator in `K[1]` and `K[2]`. They must be readable even
        // when no operator is asked, hence a three values array when `k` is
        // empty, as for a point-wise model. A tangent operator of a finite
        // strain behaviour has at least 9 values.
        let mut no_tangent = [0.0; 3];
        let k: &mut [f64] = if k.is_empty() { &mut no_tangent } else { k };
        k[0] = code
            + if options.compute_speed_of_sound {
                100.0
            } else {
                0.0
            };
        if let Some(finite_strain) = self.finite_strain {
            k[1..3].copy_from_slice(&finite_strain);
        }
        let mut message = [0_u8; ffi::ERROR_MESSAGE_SIZE];
        let mut data = ffi::BehaviourData {
            error_message: message.as_mut_ptr().cast(),
            dt: *dt,
            k: k.as_mut_ptr(),
            rdt,
            speed_of_sound,
            s0: ffi::InitialState {
                gradients: s0.gradients.as_ptr(),
                thermodynamic_forces: s0.thermodynamic_forces.as_ptr(),
                mass_density: &s0.mass_density,
                material_properties: s0.material_properties.as_ptr(),
                internal_state_variables: s0.internal_state_variables.as_ptr(),
                stored_energy: &s0.stored_energy,
                dissipated_energy: &s0.dissipated_energy,
                external_state_variables: s0.external_state_variables.as_ptr(),
            },
            s1: ffi::State {
                gradients: s1.gradients.as_ptr(),
                thermodynamic_forces: s1.thermodynamic_forces.as_mut_ptr(),
                mass_density: &s1.mass_density,
                material_properties: s1.material_properties.as_ptr(),
                internal_state_variables: s1.internal_state_variables.as_mut_ptr(),
                stored_energy: &mut s1.stored_energy,
                dissipated_energy: &mut s1.dissipated_energy,
                external_state_variables: s1.external_state_variables.as_ptr(),
            },
        };
        // SAFETY: `integrate` was read from the library with its signature at
        // load time. Every array has the length the behaviour reads or writes,
        // checked above, and outlives the call, as the scalars, borrowed from
        // `d`, and the error buffer, a local of this function.
        let status = unsafe { (self.integrate)(&mut data) };
        match status {
            1.. => Ok(Status::Reliable),
            0 => Ok(Status::Unreliable),
            _ => {
                // The buffer was zeroed, and the behaviour writes at most
                // `ERROR_MESSAGE_SIZE - 1` bytes followed by a NUL.
                let message = CStr::from_bytes_until_nul(&message)
                    .map(|m| m.to_string_lossy().into_owned())
                    .unwrap_or_default();
                Err(Error::IntegrationFailed {
                    message,
                    time_step_scaling_factor: *rdt,
                })
            }
        }
    }
}

/// Lays the variables out one after the other in an array, with the sizes
/// they have in a space of `dimension`, and the bounds the library gives.
fn layout(list: Vec<(String, VariableType)>, dimension: usize, symbols: &Symbols) -> Variables {
    let mut offset = 0;
    let list = list
        .into_iter()
        .map(|(name, variable_type)| {
            let size = match (variable_type, dimension) {
                (VariableType::Scalar, _) => 1,
                (VariableType::Vector, d) => d,
                (VariableType::Stensor | VariableType::Tensor, 1) => 3,
                (VariableType::Stensor, 2) => 4,
                (VariableType::Tensor, 2) => 5,
                (VariableType::Stensor, _) => 6,
                (VariableType::Tensor, _) => 9,
            };
            // `<variable>_LowerBound`, …, named after the array for an
            // element of an array, `b` for `b[0]`.
            let base = name.split_once('[').map_or(name.as_str(), |(base, _)| base);
            let [lower, upper, physical_lower, physical_upper] = [
                "LowerBound",
                "UpperBound",
                "LowerPhysicalBound",
                "UpperPhysicalBound",
            ]
            .map(|bound| symbols.long_double(&format!("{base}_{bound}")));
            let variable = Variable {
                variable_type,
                offset,
                size,
                bounds: Bounds { lower, upper },
                physical_bounds: Bounds {
                    lower: physical_lower,
                    upper: physical_upper,
                },
                name,
            };
            offset += size;
            variable
        })
        .collect();
    Variables { list, size: offset }
}