Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/wkt/duration.js

raw
1 // Copyright 2021-2026 Buf Technologies, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 import { DurationSchema } from "./gen/google/protobuf/duration_pb.js";
15 import { create } from "../create.js";
16 import { protoInt64 } from "../proto-int64.js";
17 /**
18 * Create a google.protobuf.Duration message from a Unix timestamp in milliseconds.
19 */
20 export function durationFromMs(durationMs) {
21 const sign = durationMs < 0 ? -1 : 1;
22 const absDurationMs = Math.abs(durationMs);
23 const absSeconds = Math.floor(absDurationMs / 1000);
24 const absNanos = (absDurationMs - absSeconds * 1000) * 1000000;
25 return create(DurationSchema, {
26 seconds: protoInt64.parse(absSeconds * sign),
27 nanos: absNanos === 0 ? 0 : absNanos * sign, // deliberately avoid signed 0 - it does not serialize
28 });
29 }
30 /**
31 * Convert a google.protobuf.Duration to a Unix timestamp in milliseconds.
32 */
33 export function durationMs(duration) {
34 return Number(duration.seconds) * 1000 + Math.round(duration.nanos / 1000000);
35 }