1 // Copyright 2021 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 15 #include "pw_snapshot/uuid.h" 16 17 #include <cstddef> 18 19 #include "pw_bytes/span.h" 20 #include "pw_protobuf/decoder.h" 21 #include "pw_result/result.h" 22 #include "pw_snapshot_metadata_proto/snapshot_metadata.pwpb.h" 23 #include "pw_span/span.h" 24 #include "pw_status/try.h" 25 26 namespace pw::snapshot { 27 28 using protobuf::Decoder; 29 ReadUuidFromSnapshot(ConstByteSpan snapshot,UuidSpan output)30Result<ConstByteSpan> ReadUuidFromSnapshot(ConstByteSpan snapshot, 31 UuidSpan output) { 32 Decoder decoder(snapshot); 33 ConstByteSpan metadata; 34 while (decoder.Next().ok()) { 35 if (decoder.FieldNumber() == 36 static_cast<uint32_t>( 37 pw::snapshot::pwpb::SnapshotBasicInfo::Fields::kMetadata)) { 38 PW_TRY(decoder.ReadBytes(&metadata)); 39 break; 40 } 41 } 42 if (metadata.empty()) { 43 return Status::NotFound(); 44 } 45 46 // Start to read from the metadata. 47 decoder.Reset(metadata); 48 ConstByteSpan snapshot_uuid; 49 while (decoder.Next().ok()) { 50 if (decoder.FieldNumber() == 51 static_cast<uint32_t>( 52 pw::snapshot::pwpb::Metadata::Fields::kSnapshotUuid)) { 53 PW_TRY(decoder.ReadBytes(&snapshot_uuid)); 54 break; 55 } 56 } 57 if (snapshot_uuid.empty()) { 58 return Status::NotFound(); 59 } 60 if (snapshot_uuid.size_bytes() > output.size_bytes()) { 61 return Status::ResourceExhausted(); 62 } 63 64 memcpy(output.data(), snapshot_uuid.data(), snapshot_uuid.size_bytes()); 65 return ConstByteSpan(output.first(snapshot_uuid.size_bytes())); 66 } 67 68 } // namespace pw::snapshot 69