xref: /aosp_15_r20/external/grpc-grpc/third_party/upb/upb/base/status.c (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 Google LLC.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 #include "upb/base/status.h"
9 
10 #include <errno.h>
11 #include <float.h>
12 #include <stdarg.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 // Must be last.
17 #include "upb/port/def.inc"
18 
upb_Status_Clear(upb_Status * status)19 void upb_Status_Clear(upb_Status* status) {
20   if (!status) return;
21   status->ok = true;
22   status->msg[0] = '\0';
23 }
24 
upb_Status_IsOk(const upb_Status * status)25 bool upb_Status_IsOk(const upb_Status* status) { return status->ok; }
26 
upb_Status_ErrorMessage(const upb_Status * status)27 const char* upb_Status_ErrorMessage(const upb_Status* status) {
28   return status->msg;
29 }
30 
upb_Status_SetErrorMessage(upb_Status * status,const char * msg)31 void upb_Status_SetErrorMessage(upb_Status* status, const char* msg) {
32   if (!status) return;
33   status->ok = false;
34   strncpy(status->msg, msg, _kUpb_Status_MaxMessage - 1);
35   status->msg[_kUpb_Status_MaxMessage - 1] = '\0';
36 }
37 
upb_Status_SetErrorFormat(upb_Status * status,const char * fmt,...)38 void upb_Status_SetErrorFormat(upb_Status* status, const char* fmt, ...) {
39   va_list args;
40   va_start(args, fmt);
41   upb_Status_VSetErrorFormat(status, fmt, args);
42   va_end(args);
43 }
44 
upb_Status_VSetErrorFormat(upb_Status * status,const char * fmt,va_list args)45 void upb_Status_VSetErrorFormat(upb_Status* status, const char* fmt,
46                                 va_list args) {
47   if (!status) return;
48   status->ok = false;
49   vsnprintf(status->msg, sizeof(status->msg), fmt, args);
50   status->msg[_kUpb_Status_MaxMessage - 1] = '\0';
51 }
52 
upb_Status_VAppendErrorFormat(upb_Status * status,const char * fmt,va_list args)53 void upb_Status_VAppendErrorFormat(upb_Status* status, const char* fmt,
54                                    va_list args) {
55   size_t len;
56   if (!status) return;
57   status->ok = false;
58   len = strlen(status->msg);
59   vsnprintf(status->msg + len, sizeof(status->msg) - len, fmt, args);
60   status->msg[_kUpb_Status_MaxMessage - 1] = '\0';
61 }
62