Skip to content

Commit c1a5e13

Browse files
hlefnwf
authored andcommitted
sntp: deduplicate error handling in ntp_time_update.
The error handling code is duplicated 4x. Use `do {...} while {false}` to factor it out at the end of the function. This frees up 160B. Signed-off-by: Hugo Lefeuvre <[email protected]>
1 parent 82c8201 commit c1a5e13

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

lib/sntp/sntp.cc

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,10 @@ namespace
334334
{
335335
static FlagLockPriorityInherited lock;
336336
NetworkContext udpContext{timeout, nullptr};
337+
SntpStatus_t status;
338+
// Use the do {...} while {false} to deduplicate
339+
// error-handling.
340+
do
337341
{
338342
if (LockGuard guard{lock, timeout})
339343
{
@@ -364,7 +368,7 @@ namespace
364368
SntpContext_t context;
365369

366370
/* Initialize context. */
367-
SntpStatus_t status =
371+
status =
368372
Sntp_Init(&context,
369373
timeServers,
370374
sizeof(timeServers) / sizeof(SntpServerInfo_t),
@@ -380,11 +384,7 @@ namespace
380384
if (status != SntpSuccess)
381385
{
382386
Debug::log("Failed to initialize SNTP client: {}", status);
383-
Timeout t{UnlimitedTimeout};
384-
network_socket_close(
385-
&t, MALLOC_CAPABILITY, udpContext.socket);
386-
timeout->elapse(t.elapsed);
387-
return ntp_error_to_errno(status);
387+
break;
388388
}
389389

390390
/* Loop of SNTP client for period time synchronization. */
@@ -393,11 +393,7 @@ namespace
393393
if (status != SntpSuccess)
394394
{
395395
Debug::log("Failed to send SNTP request: {}", status);
396-
Timeout t{UnlimitedTimeout};
397-
network_socket_close(
398-
&t, MALLOC_CAPABILITY, udpContext.socket);
399-
timeout->elapse(t.elapsed);
400-
return ntp_error_to_errno(status);
396+
break;
401397
}
402398

403399
SntpStatus_t lastStatus = SntpSuccess;
@@ -424,25 +420,22 @@ namespace
424420
{
425421
Debug::log("Failed to receive SNTP time response: {}",
426422
status);
427-
Timeout t{UnlimitedTimeout};
428-
network_socket_close(
429-
&t, MALLOC_CAPABILITY, udpContext.socket);
430-
timeout->elapse(t.elapsed);
431-
return ntp_error_to_errno(status);
423+
break;
432424
}
433425

434426
Debug::log("Received new time from NTP!");
427+
status = SntpSuccess;
435428
}
436429
else
437430
{
438431
return -ETIMEDOUT;
439432
}
440-
}
433+
} while (false);
441434
Timeout t{UnlimitedTimeout};
442435
network_socket_close(&t, MALLOC_CAPABILITY, udpContext.socket);
443436
timeout->elapse(t.elapsed);
444437
Debug::log("Closed NTP socket {}", udpContext.socket);
445-
return 0;
438+
return ntp_error_to_errno(status);
446439
}
447440

448441
} // namespace

0 commit comments

Comments
 (0)