Debian Codegraph @

src/oid.rs

raw
1 use std::cmp::Ordering;
2 use std::fmt;
3 use std::hash::{Hash, Hasher};
4 use std::path::Path;
5 use std::str;
6
7 use crate::{raw, Error, IntoCString, ObjectType};
8
9 use crate::util::{c_cmp_to_ordering, Binding};
10
11 /// Object ID format (hash algorithm).
12 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
13 #[cfg_attr(not(feature = "unstable-sha256"), non_exhaustive)]
14 pub enum ObjectFormat {
15 /// SHA1 object format (20-byte object IDs)
16 Sha1,
17 /// SHA256 object format (32-byte object IDs)
18 #[cfg(feature = "unstable-sha256")]
19 Sha256,
20 }
21
22 impl ObjectFormat {
23 /// Convert an object format to its string representation.
24 pub fn str(&self) -> &'static str {
25 match self {
26 ObjectFormat::Sha1 => "sha1",
27 #[cfg(feature = "unstable-sha256")]
28 ObjectFormat::Sha256 => "sha256",
29 }
30 }
31 }
32
33 impl fmt::Display for ObjectFormat {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 self.str().fmt(f)
36 }
37 }
38
39 impl Binding for ObjectFormat {
40 type Raw = raw::git_oid_t;
41
42 unsafe fn from_raw(raw: raw::git_oid_t) -> Self {
43 match raw {
44 raw::GIT_OID_SHA1 => ObjectFormat::Sha1,
45 #[cfg(feature = "unstable-sha256")]
46 raw::GIT_OID_SHA256 => ObjectFormat::Sha256,
47 _ => panic!("Unknown git oid type"),
48 }
49 }
50
51 fn raw(&self) -> Self::Raw {
52 match self {
53 ObjectFormat::Sha1 => raw::GIT_OID_SHA1,
54 #[cfg(feature = "unstable-sha256")]
55 ObjectFormat::Sha256 => raw::GIT_OID_SHA256,
56 }
57 }
58 }
59
60 /// Unique identity of any object (commit, tree, blob, tag).
61 #[derive(Copy, Clone)]
62 #[repr(C)]
63 pub struct Oid {
64 raw: raw::git_oid,
65 }
66
67 impl Oid {
68 /// An all-zero SHA1 OID.
69 pub const ZERO_SHA1: Oid = Oid {
70 raw: raw::git_oid {
71 #[cfg(feature = "unstable-sha256")]
72 kind: raw::GIT_OID_SHA1 as libc::c_uchar,
73 id: [0; raw::GIT_OID_MAX_SIZE],
74 },
75 };
76
77 /// An all-zero SHA256 OID.
78 #[cfg(feature = "unstable-sha256")]
79 pub const ZERO_SHA256: Oid = Oid {
80 raw: raw::git_oid {
81 kind: raw::GIT_OID_SHA256 as libc::c_uchar,
82 id: [0; raw::GIT_OID_MAX_SIZE],
83 },
84 };
85
86 /// Parse a hex-formatted object id into an Oid structure.
87 ///
88 /// This always parses as SHA1 (up to 40 hex characters). Use
89 /// [`Oid::from_str_ext`] to parse with a specific format.
90 ///
91 /// # Errors
92 ///
93 /// Returns an error if the string is empty, is longer than 40 hex
94 /// characters, or contains any non-hex characters.
95 pub fn from_str(s: &str) -> Result<Oid, Error> {
96 Self::from_str_ext(s, ObjectFormat::Sha1)
97 }
98
99 /// Parses a hex-formatted object id with a specific object format.
100 ///
101 /// # Errors
102 ///
103 /// Returns an error if the string is
104 ///
105 /// * is empty
106 /// * is longer than 40 hex with SHA1 object format
107 /// * is longer than 64 hex with SHA256 object format
108 /// * contains any non-hex characters
109 pub fn from_str_ext(s: &str, format: ObjectFormat) -> Result<Oid, Error> {
110 crate::init();
111 let mut raw = crate::util::zeroed_raw_oid();
112 let data = s.as_bytes().as_ptr() as *const libc::c_char;
113 let len = s.len() as libc::size_t;
114 unsafe {
115 #[cfg(not(feature = "unstable-sha256"))]
116 {
117 let _ = format;
118 try_call!(raw::git_oid_fromstrn(&mut raw, data, len));
119 }
120 #[cfg(feature = "unstable-sha256")]
121 try_call!(raw::git_oid_fromstrn(&mut raw, data, len, format.raw()));
122 }
123 Ok(Oid { raw })
124 }
125
126 /// Parse a raw object id into an Oid structure.
127 ///
128 /// If the array given is not 20 bytes in length, an error is returned.
129 pub fn from_bytes(bytes: &[u8]) -> Result<Oid, Error> {
130 crate::init();
131 let mut raw = crate::util::zeroed_raw_oid();
132
133 #[cfg(not(feature = "unstable-sha256"))]
134 {
135 if bytes.len() != raw::GIT_OID_SHA1_SIZE {
136 return Err(Error::from_str(&format!(
137 "raw byte array must be 20 bytes, but got {}",
138 bytes.len()
139 )));
140 }
141 unsafe {
142 try_call!(raw::git_oid_fromraw(&mut raw, bytes.as_ptr()));
143 }
144 }
145
146 #[cfg(feature = "unstable-sha256")]
147 {
148 let oid_type = match bytes.len() {
149 raw::GIT_OID_SHA1_SIZE => raw::GIT_OID_SHA1,
150 raw::GIT_OID_SHA256_SIZE => raw::GIT_OID_SHA256,
151 _ => {
152 return Err(Error::from_str(&format!(
153 "raw byte array must be 20 bytes (SHA1) or 32 bytes (SHA256), but got {}",
154 bytes.len()
155 )));
156 }
157 };
158 unsafe {
159 try_call!(raw::git_oid_fromraw(&mut raw, bytes.as_ptr(), oid_type));
160 }
161 }
162
163 Ok(Oid { raw })
164 }
165
166 /// Creates an all-zero SHA1 OID.
167 #[deprecated(since = "0.21.0", note = "use `Oid::ZERO_SHA1` instead")]
168 pub fn zero() -> Oid {
169 Self::ZERO_SHA1
170 }
171
172 /// Hashes the provided data as an object of the provided type, and returns
173 /// an Oid corresponding to the result. This does not store the object
174 /// inside any object database or repository.
175 ///
176 /// This always hashes using SHA1. Use [`Oid::hash_object_ext`]
177 /// to hash with a specific format.
178 pub fn hash_object(kind: ObjectType, bytes: &[u8]) -> Result<Oid, Error> {
179 Self::hash_object_ext(kind, bytes, ObjectFormat::Sha1)
180 }
181
182 /// Hashes the provided data as an object of the provided type,
183 /// with a specific object format.
184 ///
185 /// See [`Oid::hash_object`] for more details.
186 pub fn hash_object_ext(
187 kind: ObjectType,
188 bytes: &[u8],
189 format: ObjectFormat,
190 ) -> Result<Oid, Error> {
191 crate::init();
192
193 let mut out = crate::util::zeroed_raw_oid();
194 let data = bytes.as_ptr() as *const libc::c_void;
195 unsafe {
196 #[cfg(not(feature = "unstable-sha256"))]
197 {
198 let _ = format;
199 try_call!(raw::git_odb_hash(&mut out, data, bytes.len(), kind.raw()));
200 }
201 #[cfg(feature = "unstable-sha256")]
202 try_call!(raw::git_odb_hash(
203 &mut out,
204 data,
205 bytes.len(),
206 kind.raw(),
207 format.raw()
208 ));
209 }
210
211 Ok(Oid { raw: out })
212 }
213
214 /// Hashes the content of the provided file as an object of the provided type,
215 /// and returns an Oid corresponding to the result. This does not store the object
216 /// inside any object database or repository.
217 ///
218 /// This always hashes using SHA1. Use [`Oid::hash_file_ext`]
219 /// to hash with a specific format.
220 pub fn hash_file<P: AsRef<Path>>(kind: ObjectType, path: P) -> Result<Oid, Error> {
221 Self::hash_file_ext(kind, path, ObjectFormat::Sha1)
222 }
223
224 /// Hashes the content of a file as an object of the provided type,
225 /// with a specific object format.
226 ///
227 /// See [`Oid::hash_file`] for more details.
228 pub fn hash_file_ext<P: AsRef<Path>>(
229 kind: ObjectType,
230 path: P,
231 format: ObjectFormat,
232 ) -> Result<Oid, Error> {
233 crate::init();
234
235 // Normal file path OK (does not need Windows conversion).
236 let rpath = path.as_ref().into_c_string()?;
237
238 let mut out = crate::util::zeroed_raw_oid();
239 unsafe {
240 #[cfg(not(feature = "unstable-sha256"))]
241 {
242 let _ = format;
243 try_call!(raw::git_odb_hashfile(&mut out, rpath, kind.raw()));
244 }
245 #[cfg(feature = "unstable-sha256")]
246 try_call!(raw::git_odb_hashfile(
247 &mut out,
248 rpath,
249 kind.raw(),
250 format.raw()
251 ));
252 }
253
254 Ok(Oid { raw: out })
255 }
256
257 /// View this OID as a byte-slice in its logical length:
258 /// 20 bytes for SHA1, 32 bytes for SHA256.
259 pub fn as_bytes(&self) -> &[u8] {
260 #[cfg(not(feature = "unstable-sha256"))]
261 {
262 &self.raw.id
263 }
264 #[cfg(feature = "unstable-sha256")]
265 {
266 let size = match self.raw.kind as raw::git_oid_t {
267 raw::GIT_OID_SHA1 => raw::GIT_OID_SHA1_SIZE,
268 raw::GIT_OID_SHA256 => raw::GIT_OID_SHA256_SIZE,
269 _ => panic!("Unknown git oid type"),
270 };
271 &self.raw.id[..size]
272 }
273 }
274
275 /// Test if this OID is all zeros.
276 pub fn is_zero(&self) -> bool {
277 unsafe { raw::git_oid_is_zero(&self.raw) == 1 }
278 }
279
280 /// Returns the [`ObjectFormat`] of this OID.
281 ///
282 /// Without the `unstable-sha256` feature, this always returns
283 /// [`ObjectFormat::Sha1`].
284 pub fn object_format(&self) -> ObjectFormat {
285 #[cfg(not(feature = "unstable-sha256"))]
286 {
287 ObjectFormat::Sha1
288 }
289 #[cfg(feature = "unstable-sha256")]
290 {
291 unsafe { Binding::from_raw(self.raw.kind as raw::git_oid_t) }
292 }
293 }
294 }
295
296 impl Binding for Oid {
297 type Raw = *const raw::git_oid;
298
299 unsafe fn from_raw(oid: *const raw::git_oid) -> Oid {
300 Oid { raw: *oid }
301 }
302 fn raw(&self) -> *const raw::git_oid {
303 &self.raw as *const _
304 }
305 }
306
307 impl fmt::Debug for Oid {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 fmt::Display::fmt(self, f)
310 }
311 }
312
313 impl fmt::Display for Oid {
314 /// Hex-encode this Oid into a formatter.
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 let mut dst = [0u8; raw::GIT_OID_MAX_HEXSIZE + 1];
317 unsafe {
318 raw::git_oid_tostr(
319 dst.as_mut_ptr() as *mut libc::c_char,
320 dst.len() as libc::size_t,
321 &self.raw,
322 );
323 }
324 let s = &dst[..dst.iter().position(|&a| a == 0).unwrap()];
325 str::from_utf8(s).unwrap().fmt(f)
326 }
327 }
328
329 impl str::FromStr for Oid {
330 type Err = Error;
331
332 /// Parse a hex-formatted object id into an Oid structure.
333 ///
334 /// This always parses as SHA1.
335 /// Use [`Oid::from_str_ext`] for format-aware parsing.
336 ///
337 /// # Errors
338 ///
339 /// Returns an error if the string is empty, is longer than 40 hex
340 /// characters, or contains any non-hex characters.
341 fn from_str(s: &str) -> Result<Oid, Error> {
342 Oid::from_str(s)
343 }
344 }
345
346 impl PartialEq for Oid {
347 fn eq(&self, other: &Oid) -> bool {
348 unsafe { raw::git_oid_equal(&self.raw, &other.raw) != 0 }
349 }
350 }
351 impl Eq for Oid {}
352
353 impl PartialOrd for Oid {
354 fn partial_cmp(&self, other: &Oid) -> Option<Ordering> {
355 Some(self.cmp(other))
356 }
357 }
358
359 impl Ord for Oid {
360 fn cmp(&self, other: &Oid) -> Ordering {
361 c_cmp_to_ordering(unsafe { raw::git_oid_cmp(&self.raw, &other.raw) })
362 }
363 }
364
365 impl Hash for Oid {
366 fn hash<H: Hasher>(&self, into: &mut H) {
367 #[cfg(feature = "unstable-sha256")]
368 self.raw.kind.hash(into);
369 self.raw.id.hash(into)
370 }
371 }
372
373 impl AsRef<[u8]> for Oid {
374 fn as_ref(&self) -> &[u8] {
375 self.as_bytes()
376 }
377 }
378
379 // Double-check libgit2's OID size constants to keep the docs and the
380 // public API surface honest. If any of these break, the doc comments on
381 // `Oid::as_bytes` need to be revisited.
382 #[cfg(not(feature = "unstable-sha256"))]
383 const _: () = assert!(raw::GIT_OID_MAX_SIZE == 20);
384 #[cfg(feature = "unstable-sha256")]
385 const _: () = {
386 assert!(raw::GIT_OID_SHA1_SIZE == 20);
387 assert!(raw::GIT_OID_SHA256_SIZE == 32);
388 assert!(raw::GIT_OID_MAX_SIZE == 32);
389 };
390
391 #[cfg(test)]
392 mod tests {
393 use std::fs::File;
394 use std::io::prelude::*;
395
396 use libgit2_sys as raw;
397
398 use super::Error;
399 use super::Oid;
400 use crate::ObjectFormat;
401 use crate::ObjectType;
402 use tempfile::TempDir;
403
404 #[test]
405 fn conversions() {
406 assert!(Oid::from_str("foo").is_err());
407 assert!(Oid::from_str("decbf2be529ab6557d5429922251e5ee36519817").is_ok());
408 assert!(Oid::from_bytes(b"foo").is_err());
409 assert!(Oid::from_bytes(b"00000000000000000000").is_ok());
410 }
411
412 #[test]
413 fn conversions_ext_sha1() {
414 assert!(Oid::from_str_ext("foo", ObjectFormat::Sha1).is_err());
415 assert!(Oid::from_str_ext(
416 "decbf2be529ab6557d5429922251e5ee36519817",
417 ObjectFormat::Sha1
418 )
419 .is_ok());
420
421 let sha1 = Oid::ZERO_SHA1;
422 assert_eq!(sha1.as_bytes().len(), raw::GIT_OID_SHA1_SIZE);
423 assert_eq!(sha1.to_string().len(), raw::GIT_OID_SHA1_HEXSIZE);
424 }
425
426 #[test]
427 #[cfg(feature = "unstable-sha256")]
428 fn conversions_ext_sha256() {
429 assert!(Oid::from_str_ext("foo", ObjectFormat::Sha256).is_err());
430 assert!(Oid::from_str_ext(
431 "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
432 ObjectFormat::Sha256
433 )
434 .is_ok());
435
436 let sha256 = Oid::ZERO_SHA256;
437 assert_eq!(sha256.as_bytes().len(), raw::GIT_OID_SHA256_SIZE);
438 assert_eq!(sha256.to_string().len(), raw::GIT_OID_SHA256_HEXSIZE);
439
440 // SHA1 zero and SHA256 zero are not equal despite both being all zeros.
441 assert_ne!(Oid::ZERO_SHA1, sha256);
442 }
443
444 #[test]
445 fn object_format_always_sha1() {
446 let oid = Oid::ZERO_SHA1;
447 assert_eq!(oid.object_format(), ObjectFormat::Sha1);
448 }
449
450 #[test]
451 fn object_format_from_oid_ext_sha1() {
452 let sha1 = Oid::from_str_ext(
453 "decbf2be529ab6557d5429922251e5ee36519817",
454 ObjectFormat::Sha1,
455 )
456 .unwrap();
457 assert_eq!(sha1.object_format(), ObjectFormat::Sha1);
458 }
459
460 #[test]
461 #[cfg(feature = "unstable-sha256")]
462 fn object_format_from_oid_ext_sha256() {
463 assert_eq!(Oid::ZERO_SHA256.object_format(), ObjectFormat::Sha256);
464
465 let sha256 = Oid::from_str_ext(
466 "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
467 ObjectFormat::Sha256,
468 )
469 .unwrap();
470 assert_eq!(sha256.object_format(), ObjectFormat::Sha256);
471 }
472
473 #[test]
474 fn comparisons() -> Result<(), Error> {
475 assert_eq!(Oid::from_str("decbf2b")?, Oid::from_str("decbf2b")?);
476 assert!(Oid::from_str("decbf2b")? <= Oid::from_str("decbf2b")?);
477 assert!(Oid::from_str("decbf2b")? >= Oid::from_str("decbf2b")?);
478 {
479 let o = Oid::from_str("decbf2b")?;
480 assert_eq!(o, o);
481 assert!(o <= o);
482 assert!(o >= o);
483 }
484 assert_eq!(
485 Oid::from_str("decbf2b")?,
486 Oid::from_str("decbf2b000000000000000000000000000000000")?
487 );
488 assert!(
489 Oid::from_bytes(b"00000000000000000000")? < Oid::from_bytes(b"00000000000000000001")?
490 );
491 assert!(Oid::from_bytes(b"00000000000000000000")? < Oid::from_str("decbf2b")?);
492 assert_eq!(
493 Oid::from_bytes(b"00000000000000000000")?,
494 Oid::from_str("3030303030303030303030303030303030303030")?
495 );
496 Ok(())
497 }
498
499 #[test]
500 fn comparisons_ext_sha1() -> Result<(), Error> {
501 let a = Oid::from_str_ext("decbf2b", ObjectFormat::Sha1)?;
502 let b = Oid::from_str_ext(
503 "decbf2b000000000000000000000000000000000",
504 ObjectFormat::Sha1,
505 )?;
506 assert_eq!(a, b);
507 assert!(a <= b);
508 assert!(a >= b);
509 assert!(Oid::from_bytes(b"00000000000000000000")? < a);
510 Ok(())
511 }
512
513 #[test]
514 #[cfg(feature = "unstable-sha256")]
515 fn comparisons_ext_sha256() -> Result<(), Error> {
516 const HEX: &str = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
517
518 let a = Oid::from_str_ext(HEX, ObjectFormat::Sha256)?;
519 let b = Oid::from_str_ext(HEX, ObjectFormat::Sha256)?;
520 assert_eq!(a, b);
521 assert!(a <= b);
522 assert!(a >= b);
523
524 assert_eq!(
525 Oid::from_str_ext("abcdef12", ObjectFormat::Sha256)?,
526 Oid::from_str_ext(
527 "abcdef1200000000000000000000000000000000000000000000000000000000",
528 ObjectFormat::Sha256
529 )?
530 );
531
532 // SHA256 byte comparisons (32 bytes)
533 assert!(
534 Oid::from_bytes(b"00000000000000000000000000000000")?
535 < Oid::from_bytes(b"00000000000000000000000000000001")?
536 );
537 assert!(Oid::from_bytes(b"00000000000000000000000000000000")? < a);
538 Ok(())
539 }
540
541 #[test]
542 fn zero_is_zero() {
543 assert!(Oid::ZERO_SHA1.is_zero());
544 assert_eq!(Oid::ZERO_SHA1.object_format(), ObjectFormat::Sha1);
545 }
546
547 #[test]
548 #[cfg(feature = "unstable-sha256")]
549 fn zero_sha256_is_zero() {
550 assert!(Oid::ZERO_SHA256.is_zero());
551 assert_eq!(Oid::ZERO_SHA256.object_format(), ObjectFormat::Sha256);
552 }
553
554 #[test]
555 fn hash_object() {
556 let bytes = "Hello".as_bytes();
557 let oid = Oid::hash_object(ObjectType::Blob, bytes).unwrap();
558 assert_eq!(oid.to_string().len(), raw::GIT_OID_SHA1_HEXSIZE);
559 assert_eq!(oid.as_bytes().len(), raw::GIT_OID_SHA1_SIZE);
560 }
561
562 #[test]
563 fn hash_object_ext_sha1() -> Result<(), Error> {
564 let oid = Oid::hash_object_ext(ObjectType::Blob, b"hello world", ObjectFormat::Sha1)?;
565 assert_eq!(oid.to_string().len(), raw::GIT_OID_SHA1_HEXSIZE);
566 assert_eq!(oid.as_bytes().len(), raw::GIT_OID_SHA1_SIZE);
567 Ok(())
568 }
569
570 #[test]
571 #[cfg(feature = "unstable-sha256")]
572 fn hash_object_ext_sha256() -> Result<(), Error> {
573 let bytes = b"hello world";
574 let sha1 = Oid::hash_object_ext(ObjectType::Blob, bytes, ObjectFormat::Sha1)?;
575 let sha256 = Oid::hash_object_ext(ObjectType::Blob, bytes, ObjectFormat::Sha256)?;
576 assert_eq!(sha256.to_string().len(), raw::GIT_OID_SHA256_HEXSIZE);
577 assert_eq!(sha256.as_bytes().len(), raw::GIT_OID_SHA256_SIZE);
578 assert_ne!(sha1, sha256);
579 Ok(())
580 }
581
582 #[test]
583 fn hash_file() {
584 let td = TempDir::new().unwrap();
585 let path = td.path().join("hello.txt");
586 let mut file = File::create(&path).unwrap();
587 file.write_all("Hello".as_bytes()).unwrap();
588 let oid = Oid::hash_file(ObjectType::Blob, &path).unwrap();
589 assert_eq!(oid.to_string().len(), raw::GIT_OID_SHA1_HEXSIZE);
590 assert_eq!(oid.as_bytes().len(), raw::GIT_OID_SHA1_SIZE);
591 }
592
593 #[test]
594 fn hash_file_ext_sha1() -> Result<(), Error> {
595 let td = TempDir::new().unwrap();
596 let path = td.path().join("test.txt");
597 let mut file = File::create(&path).unwrap();
598 file.write_all(b"test content").unwrap();
599
600 let oid = Oid::hash_file_ext(ObjectType::Blob, &path, ObjectFormat::Sha1)?;
601 assert_eq!(oid.to_string().len(), raw::GIT_OID_SHA1_HEXSIZE);
602 assert_eq!(oid.as_bytes().len(), raw::GIT_OID_SHA1_SIZE);
603 Ok(())
604 }
605
606 #[test]
607 #[cfg(feature = "unstable-sha256")]
608 fn hash_file_ext_sha256() -> Result<(), Error> {
609 let td = TempDir::new().unwrap();
610 let path = td.path().join("test.txt");
611 let mut file = File::create(&path).unwrap();
612 file.write_all(b"test content").unwrap();
613
614 let sha1 = Oid::hash_file_ext(ObjectType::Blob, &path, ObjectFormat::Sha1)?;
615 let sha256 = Oid::hash_file_ext(ObjectType::Blob, &path, ObjectFormat::Sha256)?;
616 assert_eq!(sha256.to_string().len(), raw::GIT_OID_SHA256_HEXSIZE);
617 assert_eq!(sha256.as_bytes().len(), raw::GIT_OID_SHA256_SIZE);
618 assert_ne!(sha1, sha256);
619 Ok(())
620 }
621 }