Encode with the versioned layout. The version byte leads the value so future formats can be detected instead of misdecoded; v2 appends the state-bound export field after the v1 layout. CB-10A review R7: the encoder validates its own fields — the scope byte must be a real [`ViewScope`], oid fields must be hex of the known Git digest widths, state fields must be base32, and ref names must be well-f
(&self)
| 127 | /// must be well-formed — so a malformed row can never enter storage |
| 128 | /// through this build. |
| 129 | pub fn encode(&self) -> PristineResult<Vec<u8>> { |
| 130 | if self.version != REF_MAPPING_VERSION { |
| 131 | return Err(PristineError::Serialization { |
| 132 | message: format!( |
| 133 | "cannot encode ref mapping version {} (this build supports {REF_MAPPING_VERSION})", |
| 134 | self.version |
| 135 | ), |
| 136 | }); |
| 137 | } |
| 138 | if ViewScope::from_u8(self.scope).is_none() { |
| 139 | return Err(PristineError::Serialization { |
| 140 | message: format!( |
| 141 | "ref mapping scope byte {} is not a known ViewScope", |
| 142 | self.scope |
| 143 | ), |
| 144 | }); |
| 145 | } |
| 146 | if self.view_name.is_empty() || self.view_name.bytes().any(|b| b < 0x20 || b == 0x7f) { |
| 147 | return Err(PristineError::Serialization { |
| 148 | message: "ref mapping view name is empty or contains control characters" |
| 149 | .to_string(), |
| 150 | }); |
| 151 | } |
| 152 | validate_ref_name(self.local_ref.as_deref())?; |
| 153 | if let Some((remote, reference)) = &self.remote { |
| 154 | validate_ref_name(Some(reference))?; |
| 155 | if remote.is_empty() || remote.bytes().any(|b| b < 0x20 || b == 0x7f) { |
| 156 | return Err(PristineError::Serialization { |
| 157 | message: "ref mapping remote name is empty or contains control characters" |
| 158 | .to_string(), |
| 159 | }); |
| 160 | } |
| 161 | } |
| 162 | for oid in [ |
| 163 | self.last_observed_local.as_deref(), |
| 164 | self.last_observed_remote.as_deref(), |
| 165 | self.last_exported.as_deref(), |
| 166 | ] { |
| 167 | validate_oid(oid)?; |
| 168 | } |
| 169 | for state in [ |
| 170 | self.last_exported_state.as_deref(), |
| 171 | self.last_observed_atomic.as_deref(), |
| 172 | ] { |
| 173 | validate_state(state)?; |
| 174 | } |
| 175 | let mut bytes = Vec::with_capacity(128); |
| 176 | bytes.push(self.version); |
| 177 | bytes.extend_from_slice(&self.view_id.to_le_bytes()); |
| 178 | encode_len_prefixed(&mut bytes, self.view_name.as_bytes())?; |
| 179 | bytes.push(self.scope); |
| 180 | encode_option_ref(&mut bytes, self.local_ref.as_deref())?; |
| 181 | match &self.remote { |
| 182 | None => bytes.push(0), |
| 183 | Some((remote, reference)) => { |
| 184 | bytes.push(1); |
| 185 | encode_len_prefixed(&mut bytes, remote.as_bytes())?; |
| 186 | encode_len_prefixed(&mut bytes, reference.as_bytes())?; |